Home > Back-end >  Typescript how to return key type
Typescript how to return key type

Time:04-12

I can’t find information on how to correctly return exactly the type of a certain property of the type, passing the key in another field.

Can someone tell me or point out what I'm doing wrong? :(

type TUser = {
    age: number,
    initials: {
        name: string
    }
}

type TRendererFunctionArgs<TValues> = {
    value: TValues[keyof TValues],
}

type TRenderer<TValues> = {
    name: keyof TValues,
    renderer: ({ value }: TRendererFunctionArgs<TValues>) => string,
}

const renderer : TRenderer<TUser> = {
    name: 'initials',
    renderer: ({ value }) => value.name, // <--- There is problem because. value : value: number | {name: string}
}

Playground link

CodePudding user response:

Here's an approach that uses a mapped type as an indexed access type:

type TUser = {
    age: number,
    initials: {
        name: string
    }
}

type TRenderer<TValues> = { [K in keyof TValues]-?: {
    name: K;
    renderer: ({ value }: { value: TValues[K] }) => string;
} }[keyof TValues];

const renderer : TRenderer<TUser> = {
    name: 'initials',
    renderer: ({ value }) => value.name
}
  • Related