在 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
Author 回答者: shfshanyue
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
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];
};