如何通过 TypeScript 中的映射类型删除属性 [英] how to remove properties via mapped type in TypeScript

查看:23
本文介绍了如何通过 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 替换它

I want to remove " visible / x / y " properties via RemoveProperties ,but I can only replace it with never

推荐答案

您可以使用与 Omit 类型使用:

You can use the same trick as the Omit type uses:

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

这篇关于如何通过 TypeScript 中的映射类型删除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆