You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
typeMyOmit<T,KeyextendskeyofT>={[K2inkeyofTas(K2extendsKey ? never : K2)]: T[K2];};
[K2 in keyof T as (K2 extends Key ? never : K2)] 表示对于 T 类型的每个键 K2,如果 K2 是 Key 类型的子类型,则将其键名更改为 never 类型,否则保持不变。由于 never 类型是所有类型的子类型,所以这相当于从新类型中排除了 Key 指定的键。
解法一:使用 key remapping in mapped types 语法
[K2 in keyof T as (K2 extends Key ? never : K2)]
表示对于T
类型的每个键K2
,如果K2
是Key
类型的子类型,则将其键名更改为never
类型,否则保持不变。由于never
类型是所有类型的子类型,所以这相当于从新类型中排除了Key
指定的键。解法二:借助
Exclude
和Pick
将
MyOmit
的实现转化为从类型 T 中筛选出符合条件的属性;Exclude<keyof T, Key>
会从T
类型的所有键中排除Key
指定的键,然后Pick<T, Exclude<keyof T, Key>>
会从T
类型中选择剩余的键,构造一个新的类型。The text was updated successfully, but these errors were encountered: