Turn typescript interface property types into union

Viewed 536

I have this interface, and I would like to generate a new type from the type of keys it contains.

interface SomeType {
  abc: string;
  def: number;
  ghi: boolean;
}

Type to generate:

type SomeOtherType = string | number | boolean

Is this possible in typescript?

2 Answers

You can use a trick to generate the values of an interface:

interface SomeType {
  abc: string;
  def: number;
  ghi: boolean;
}

//First generate a type that works as a "valueof" (similar to keyof)
type ValueOf<T> = T[keyof T];

//Then obtain the values
type Values = ValueOf<SomeType> // Values = string | number | boolean
//ValueOf re-usable component, however it is enough also SomeType[keyof SomeType]

//If you need the keys on the other hand "keyof" is enough:
type Keys = keyof SomeType // Keys = 'abc' | 'def' | 'ghi'
Related