1

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?

1 Answer 1

1

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

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

1 Comment

Glad to help! The second thing seems be possible, but to keep this question clear, I'd suggest creating a new question for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.