[英]Argument of function is a property that exists in a type of Typescript
我想编写一个 function ,它返回一个类型上存在的单个属性:
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
似乎这种工作,但它似乎不是最好的解决方案:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.