Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3 - 实现 Omit(两种解法) #28788

Open
heavenly-zy opened this issue Jul 11, 2023 · 0 comments
Open

3 - 实现 Omit(两种解法) #28788

heavenly-zy opened this issue Jul 11, 2023 · 0 comments
Labels
3 answer Share answers/solutions to a question zh-CN 简体中文

Comments

@heavenly-zy
Copy link

heavenly-zy commented Jul 11, 2023

解法一:使用 key remapping in mapped types 语法

type MyOmit<T, Key extends keyof T> = {
  [K2 in keyof T as (K2 extends Key ? never : K2)]: T[K2];
};

[K2 in keyof T as (K2 extends Key ? never : K2)] 表示对于 T 类型的每个键 K2,如果 K2Key 类型的子类型,则将其键名更改为 never 类型,否则保持不变。由于 never 类型是所有类型的子类型,所以这相当于从新类型中排除了 Key 指定的键。

解法二:借助 ExcludePick

type MyOmit<T, Key extends keyof T> = Pick<T, Exclude<keyof T, Key>>;

MyOmit 的实现转化为从类型 T 中筛选出符合条件的属性;Exclude<keyof T, Key> 会从 T 类型的所有键中排除 Key 指定的键,然后 Pick<T, Exclude<keyof T, Key>> 会从 T 类型中选择剩余的键,构造一个新的类型。

@heavenly-zy heavenly-zy added answer Share answers/solutions to a question zh-CN 简体中文 labels Jul 11, 2023
@github-actions github-actions bot added the 3 label Jul 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
3 answer Share answers/solutions to a question zh-CN 简体中文
Projects
None yet
Development

No branches or pull requests

1 participant