极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

# 在 Typescript 中如何实现类型标记 Pick 与 Omit

更多描述

有以下测试用例

interface User {
  id: number;
  age: number;
  name: string;
}

// 相当于: type PickUser = { age: number; name: string; }
type OmitUser = Omit<User, "id">;

// 相当于: type PickUser = { id: number; age: number; }
type PickUser = Pick<User, "id" | "age">;

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 695 (opens new window)

type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};

type Exclude<T, U> = T extends U ? never : T;

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
interface User {
  id: number;
  age: number;
  name: string;
}

// 相当于: type PickUser = { age: number; name: string; }
type OmitUser = Omit<User, "id">;

// 相当于: type PickUser = { id: number; age: number; }
type PickUser = Pick<User, "id" | "age">;

Author

回答者: Asarua (opens new window)

type MyPick<O extends object, K extends keyof O> = {
  [P in K]: O[P];
};

type MyOmit<O extends object, K extends keyof O> = MyPick<
  O,
  Exclude<keyof O, K>
>;

type MyOmit2<O extends object, K extends keyof O> = {
  [P in Exclude<keyof O, K>]: O[P];
};
Last Updated: 11/27/2021, 6:11:48 PM