繁体   English   中英

类型:仅从类中提取属性,包括任何

[英]Type : Extract only properties from class including any

我正在尝试从类中提取属性以创建类型。

ts-essentialOmitProperties一起非常方便!

只有我的问题是OmitProperties<T, Function>不仅会删除类方法,还会删除any类型的每个属性。

type GetProperties<T> = OmitProperties<T, Function>

class Foo {
    foo: string = '';
    bar: any | null = null;
}

export type FooProperties = GetProperties<Foo>; //  only { foo: string; } =(

知道如何改进它以包含每个属性,包括键入为 any 的属性吗?

操场

使用unknown代替any (实际上,这适用于几乎任何使用any的情况):

class Foo {
    foo: string = '';
    bar: unknown | null = null;
}

export type FooProperties = GetProperties<Foo>; //  only { foo: string; } =(

// type FooProperties = {
//    foo: string;
//    bar: unknown | null;
// }

您可以修改PickKeysByValue类型以忽略any类型。

type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N; 

type PickKeysByValue<T, V> = { 
  [K in keyof T]: IfAny<T[K], never, T[K] extends V ? K : never> 
}[keyof T];
export type FooProperties = GetProperties<Foo>;
// type FooProperties = {
//     foo: string;
//     bar: any | null;
// }

操场


还要记住,任何键入的内容都像any | null any | null只会折叠到any

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM