Home > Blockchain >  Create a type from value of one property in an array of objects
Create a type from value of one property in an array of objects

Time:01-05

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"

CodePudding user response:

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

CodePudding user response:

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

type ActionTypes = Actions["type"];
  • Related