Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading