0

Is there a way to extract a particular property of a union type and create a type from that?

Let's say we have this:

type Actions =
  | {
  type: "ADD_COLUMN";
  newColumnIndex: number;
  column: SelectorColumnData;
}
  | {
  type: "ITEM_CHECKED";
  columnIndex: number;
  item: SelectorItem;
};

Is there some magic generic stuff we can use to produce something like:

type ActionTypes = GetTypes<Actions>
// ActionTypes = "ADD_COLUMN" | "ITEM_CHECKED"
1
  • 1
    Actions["type"] - However, if one of the constituents of Actions does not have a type property, it'll be a little more complicated. You would have to extract all constituents first: Extract<Actions, { type: any }>["type"]. Commented Jan 4, 2023 at 16:52

2 Answers 2

2

You can get all possible values of a key from union of objects by just accessing a property from the type. As mentioned in the comments it can be done using :

Action["type"];

But if you really want to create a type. You will have to use extends too, so TS can let you safely access the property.

type Actions =
  | {
  type: "ADD_COLUMN";
  newColumnIndex: number;
  column: string;
}
  | {
  type: "ITEM_CHECKED";
  columnIndex: number;
  item: string;
};

type GetTypes<T extends { type : string }> =  T['type'];


type ActionTypes = GetTypes<Actions>

Playground

Sign up to request clarification or add additional context in comments.

Comments

0

Ok, found the answer elsewhere. Doesn't even require generics:

type ActionTypes = Actions["type"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.