简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM