我想编写一个函数,该函数返回类型上存在的单个属性:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句