如何在打字稿中获取 T 的 colculated keyof 的类型作为通用类型

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

我有这两个接口

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*/
}

这是我在其他地方的用例

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*/{
        //
    }
}

我想使 save() return 类型与 id 的 return 类型相同,但以通用类型安全的方式我该怎么做?

您可以在编译时声明另一个采用属性名称的通用参数。

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];
}

然后这样使用

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