【问题标题】:how to remove properties via mapped type in TypeScript如何通过 TypeScript 中的映射类型删除属性
【发布时间】:2018-08-30 01:20:00
【问题描述】:

这里是代码

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!

我想通过 RemoveProperties 删除“可见 / x / y”属性,但我只能用 never 替换它

【问题讨论】:

    标签: typescript typescript-typings mapped-types


    【解决方案1】:

    您可以使用与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>>; 
    

    【讨论】:

    【解决方案2】:

    TS 4.1

    您可以在mapped types 中使用as clauses 一次性过滤掉属性:

    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 子句可以用作过滤器 [.]

    更多信息:Announcing TypeScript 4.1 - Key Remapping in Mapped Types

    Playground

    【讨论】:

      猜你喜欢
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 2020-05-02
      • 2020-09-08
      • 2021-08-27
      • 1970-01-01
      相关资源
      最近更新 更多