6

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Would it be simple in case the object's members are all of the same type ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.