我想编写一个函数,该函数返回存在于某个类型的单个属性: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") // OKgetBooleanValue(obj, "property2") // ERROR, TypeScript won't allow this
1 回答
精慕HU
TA贡献1845条经验 获得超8个赞
似乎这种工作,但它似乎不是最好的解决方案:
type FilterFlags<Base, Condition> = {
[Key in keyof Base]: Base[Key] extends Condition ? Key : never;
};
type AllowedNames<Base, Condition> = FilterFlags<Base, Condition>[keyof Base];
private getValue(
obj,
key: keyof AllowedNames<CustomType, boolean>
): boolean {
const value = this.getData(obj)[key];
// do stuff
return value;
}
编辑:我发现了一篇关于过滤类型(条件类型)道具的好文章:https : //medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c
添加回答
举报
0/150
提交
取消