繁体   English   中英

如何在 typescript 中获取 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()返回类型与 id 的返回类型相同,但是以通用类型安全的方式我该怎么做?

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

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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM