Sunny-117/js-challenges

myPick

FailurMan opened this issue · 3 comments

//实现ts中的内置方法pick
interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type MyPick<T, K extends keyof T> = {
  [P in K]: T[P];
};
type TodoPreview = MyPick<Todo, "title" | "completed">;
interface User {
    id: number;
    name: string;
    password: string;
}

type MyPick<T, K extends keyof T> = {
    [P in K]: T[P]
    // P in K 相当于for in语法
}

type mypicker = MyPick<User, "id" | "name">;
type MyPick<T, K extends keyof T> = {
    [p in K]:T[p]
}

type MyPick<T extends Record<string, any>, U extends keyof T> = {
[K in U]: T[K];
};

加了点小约束 pick 主要就是只保留传入的键类型