简体   繁体   中英

Typescript how to return key type

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

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
}

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