我想通过使用keyof
功能和never
来排除方法,但这不起作用:
class A {
prop = 1;
save() {}
hello() {}
}
type ExcludeFunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? never : T[K]
};
function test<T>(param: T): ExcludeFunctionPropertyNames<T> {
return { } as any;
}
test(new A()).prop; // I still see here `save` and `hello`
我的理解是never
应该删除它们。
答案 0 :(得分:1)
这里是您尝试做的一种解决方案:
class A {
prop = 1;
save() {}
hello() {}
}
type ExcludeFunctionPropertyNames<T> = Pick<T, {
[K in keyof T]: T[K] extends Function ? never : K
}[keyof T]>;
function test<T>(param: T): ExcludeFunctionPropertyNames<T> {
return { } as any;
}
test(new A()) // only prop available;
您在本文中有所有解释:https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c