[英]Is there a type-level way to extract properties that have default from a class?
[英]Type : Extract only properties from class including any
我正在尝试从类中提取属性以创建类型。
ts-essential
与OmitProperties
一起非常方便!
只有我的问题是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.