Paulo Soares
Paulo Soares

Reputation: 135

TypeScript Iterate over object and create a type from the values

Given I have an object like this:

const props = [
    { name: 'car', list: { brand: 'audi', model: 's4' }
    { name: 'motorcycle', list: { type: 'ktm', color: 'orange' }
] as constant;

I want to create a type that represents something like this:

type Props = {
    car?: 'brand' | 'model',
    motorcycle?: 'type' | 'color'
};

The closest I got was something like this:

type Props = Partial<Record<typeof props[number]['name'], typeof props[number]['list']>

But returns something like this:

type Props = {
    car?: { brand: 'audi', model: 's4' } | { type: 'ktm' | color: 'orange' } | undefined,
    motorcycle?: { brand: 'audi', model: 's4' } | { type: 'ktm' | color: 'orange' } | undefined
}

How can I achieve the desired result?

Upvotes: 1

Views: 480

Answers (1)

Oblosys
Oblosys

Reputation: 15106

You can use key remapping that was introduced in TypeScript 4.1 (docs) to achieve this:

type IndexKeys<T> = Exclude<keyof T, keyof []>
type ListProp = { name: string, list: object }
type GetName<P> = P extends ListProp ? P['name'] : never
type GetListKeys<P> = P extends ListProp ? keyof P['list'] : never

type PropsFromList<PropList extends ReadonlyArray<ListProp>> = {
  [i in IndexKeys<PropList> as GetName<PropList[i]>]?: GetListKeys<PropList[i]>
}

type Props = PropsFromList<typeof props>
// Inferred type:
// Props: {
//     car?: "brand" | "model" | undefined;
//     motorcycle?: "type" | "color" | undefined;
// }

Note that just like when using Partial, the optional property types get an extra but harmless | undefined.

TypeScript playground

Upvotes: 1

Related Questions