函数的参数是存在于 Typescript 类型中的属性

我想编写一个函数,该函数返回存在于某个类型的单个属性:


type CustomType = {

    property1: boolean;

    property2: numeric;

};


private getData(obj): CustomType {

    // do stuff

    return dataObj;

}


private getBooleanValue(obj, key): boolean {

    const value = this.getData(obj)[key];

    // do stuff

    return value;

}

我想对 getBooleanValue 的键进行限制,该键是 CustomType 的一部分 - 例如:


getBooleanValue(obj, "property1") // OK

getBooleanValue(obj, "property2") // ERROR, TypeScript won't allow this


杨魅力
浏览 199回答 1
1回答

精慕HU

似乎这种工作,但它似乎不是最好的解决方案:type FilterFlags<Base, Condition> = {&nbsp; &nbsp; [Key in keyof Base]: Base[Key] extends Condition ? Key : never;};type AllowedNames<Base, Condition> = FilterFlags<Base, Condition>[keyof Base];private getValue(&nbsp; &nbsp; obj,&nbsp;&nbsp; &nbsp; key: keyof AllowedNames<CustomType, boolean>): boolean {&nbsp; &nbsp; const value = this.getData(obj)[key];&nbsp; &nbsp; // do stuff&nbsp; &nbsp; return value;}编辑:我发现了一篇关于过滤类型(条件类型)道具的好文章:https : //medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript