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

2. MyOmit #4

Open
astak16 opened this issue Mar 31, 2022 · 0 comments
Open

2. MyOmit #4

astak16 opened this issue Mar 31, 2022 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Mar 31, 2022

题目

题目链接:MyOmit

实现一个 MyOmit 满足测试用例 cases

  • Expected1 满足两个属性:titlecompleted
  • Expected2 满足一个属性:title
type cases = [
  Expect<Equal<Expected1, MyOmit<Todo, "description">>>,
  Expect<Equal<Expected2, MyOmit<Todo, "description" | "completed">>>
];

// @ts-expect-error
type error = MyOmit<Todo, "description" | "invalid">;

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

interface Expected1 {
  title: string;
  completed: boolean;
}

interface Expected2 {
  title: string;
}

答案

方法一

type MyOmit<Type, Keys extends keyof Type> = Pick<
  Type,
  Exclude<keyof Type, Keys>
>;

解析

使用 PickExclude 可以实现 Omit

  1. Exclude<keyof Type, Keys> 使用 Exclude 剔除掉 Type 中的 key
  2. Pick<Type, Exclude<keyof Type, Keys>> 使用 Pick 挑选出 1 中的结果

方法二

type MyOmit<Type, Keys extends keyof Type> = {
  [key in Exclude<keyof Type, Keys>]: Type[key];
};

解析

使用 Exclude 可以实现 Omit

  1. Exclude<keyof Type, Keys> 使用 Exclude 剔除掉 Type 中的 Keys
  2. 使用 in 遍历 1 中的结果
  3. 使用和对象一样的取值方法 Type[key]

基础知识

  1. extends 用法
  2. Pick
  3. Exclude
  4. Omit
  5. Omit、Pick、Exclude 的区别
@astak16 astak16 added the medium label Mar 31, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant