Orelus
Orelus

Reputation: 1023

Typescript Object type to Array type

What is the correct way to transform an object type to an array of objects, each one containing one key of the object ?

For instance I want to transform

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

into

type MyObjectArrayType = { key: 'foo', value: number} | { key: 'bar', value: string}

so that I can do

const objects: MyObjectArrayType[] = [{key: 'foo', value: 2}, {key: 'bar', value: 'baz'}]

I was thinking about something like

type MyObjectArrayType<K extends keyof MyObjectType> = { value: MyObjectType[K], key: K }

but can't get it to work like I want.

Upvotes: 5

Views: 362

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250366

You can use a mapped type to generate each member of the union (for each property) and the use an index type to get all the value types in the mapped type.

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

type PropUnion<T> = {
  [K in keyof T]: { value: T[K], key: K }
}[keyof T]

type MyObjectArrayType = PropUnion<MyObjectType>;
const objects: MyObjectArrayType[] = [{key: 'foo', value: 2}, {key: 'bar', value: 'baz'}]

Playground Link

Upvotes: 3

Related Questions