3

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?

gibo
  • 527
  • 2
  • 5
  • 22

2 Answers2

5

You can try to index with a keyof operator:

interface SomeType {
  abc: string;
  def: number;
  ghi: "sdf";
}

type t = SomeType[keyof SomeType];

The type t will be assumed as a type union that comes from the values of the object: enter image description here

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgMoHsC2EAqBPABxQG8AoZZOAIwQC5kBnMKUAcwG5zkATCGekAFdMVaJwqsAFsHoAiBtxizOAX1KkwhFGGQBeNFlxaA2gGsIedDAPZ8RALrsgA

DasKrümelmonster
  • 5,816
  • 1
  • 24
  • 45
3

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'
AndreaCostanzo1
  • 1,799
  • 1
  • 12
  • 30