如何在TypeScript中通过映射类型删除属性

Wan*_*ang 9 typescript typescript-typings mapped-types

这是代码

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!
Run Code Online (Sandbox Code Playgroud)

我想通过RemoveProperties删除"visible/x/y"属性,但我只能用never替换它

for*_*d04 25

TS 4.1

您可以使用as子句映射类型一气呵成筛选出的属性:

type Methods<T> = { [P in keyof T as T[P] extends Function ? P : never]: T[P] };
type A_Methods = Methods<A>;  // { render: () => void; }
Run Code Online (Sandbox Code Playgroud)

as子句中指定的类型解析为 时never,不会为该键生成任何属性。因此,as子句可以用作过滤器 [.]

更多信息: 宣布 TypeScript 4.1 - 映射类型中的键重映射

操场

  • 在上面的 TS 4.7+ 中,这种模式开始[引起问题](https://github.com/microsoft/TypeScript/issues/51141)。知道为什么吗? (2认同)

Tit*_*mir 20

您可以使用与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>>; 
Run Code Online (Sandbox Code Playgroud)