![](/img/trans.png)
[英]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.