簡體   English   中英

如何通過 TypeScript 中的映射類型刪除屬性

[英]how to remove properties via mapped type in TypeScript

這是代碼

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 刪除“visible / x / y”屬性,但我只能用 never 替換它

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

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; }

as子句中指定的類型解析為never ,不會為該鍵生成任何屬性。 因此, as子句可以用作過濾器 [.]

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

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM