Home > Software engineering >  How do I convert a TypeScript object, into a union of objects with the key
How do I convert a TypeScript object, into a union of objects with the key

Time:05-19

I have this type:

type something = {
  a: number,
  b: string,
  c: "literal"
}

And want this type:

{
  key: "a",
  value: number
} | {
  key: "b",
  value: string
} | 
  key: "c",
  value: "literal"
}

Which I can do with a helper type:

type helper = {
  [k in keyof something]: {
    key: k,
    value: something[k]
  }
}

type keysAndValues = helper[keyof helper]

Is there a simpler way I can achieve this, without using a helper type?

CodePudding user response:

Well, to get rid of the "helper type" you can just put it inside a single type.

type KeysAndValues = {
  [k in keyof Something]: {
    key: k,
    value: Something[k]
  }
}[keyof Something]
  • Related