Search code examples
typescriptmapped-types

Is it possible to create union key value type from object type?


For example I have object type

type FooBar = {
  foo: number,
  bar: string
}

and I want to create this type

{key: "foo", value: number} | {key: "bar", value: string}

I can create

{key: keyof FooBar}

and

{value: FooBar[keyof FooBar]}

But I want to combine them somehow.


Solution

  • You can do this with a mapped type. Map each key to a {key: <keyname>, value: <keytype>} type, then build the union of all those using keyof:

    type FooBar = {
      foo: number,
      bar: string
    }
    
    type KV<T> = {[K in keyof T]: {key: K, value: T[K]}}[keyof T];
    
    declare const test: KV<FooBar>;
    // `test` has type: {key: "foo", value: number} | {key: "bar", value: string}