这是代码
class A {
x = 0;
y = 0;
visible = false;
render() {
}
}
type RemoveProperties<T> = {
readonly [P in keyof T]: T[P] extends Function ? T[P] : never//;
};
var a = new A() as RemoveProperties<A>
a.visible // never
a.render() // ok!
我想删除&#34;可见/ x / y&#34;属性通过RemoveProperties,但我只能用never
替换它答案 0 :(得分:16)
您可以使用Omit
类型使用的相同技巧:
// We take the keys of P and if T[P] is a Function we type P as P (the string literal type for the key), otherwise we type it as never.
// Then we index by keyof T, never will be removed from the union of types, leaving just the property keys that were not typed as never
type JustMethodKeys<T> = ({[P in keyof T]: T[P] extends Function ? P : never })[keyof T];
type JustMethods<T> = Pick<T, JustMethodKeys<T>>;
答案 1 :(得分:5)
您现在可以使用as
clauses中的mapped types一口气过滤掉属性:
type Methods<T> = { [P in keyof T as T[P] extends Function ? P : never]: T[P] };
type A_Methods = Methods<A>; // { render: () => void; }
当
as
子句中指定的类型解析为never
时,不会为该键生成任何属性。因此,as
子句可以用作过滤器[。]