Skip to content

how to get type of a colculated keyof T as a generic type in typescript

I have these two interfaces

interface PersonRequirements{
    user:string,
    password:string,
    id:number
}
export interface Requirement<R> {
    name: keyof R & string,
    save: () => any,/* I want this return type to be same as return type of founded key in R*/
}

and here is my use case elsewhere

const idRequirement:Requirement<PersonRequirements>={
    name:"id",
    save:function ():number/* I want this return type to be same as id's return type(number) but in a generic type safe way*/{
        //
    }
}

I want to make save() return type to be same as id’s return type but in a generic type safe way how can I do that ?

Answer

You can declare another generic parameter that takes the property name in at compile time.

export interface Requirement<R, N extends keyof R & string> {
    name: N; // this will force the name property to be the same as being passed in
    save(): R[N];
}

Then using it like this

const idRequirement: Requirement<PersonRequirements, "id"> ={
    name: "id",
    save: () => 0
}