首页 > 其他分享 >Typescript类型体操 - Pick

Typescript类型体操 - Pick

时间:2022-09-01 20:35:40浏览次数:87  
标签:Typescript string title completed 体操 Pick type TodoPreview

题目要求

实现 TS 内置的 Pick<T, K>,但不可以使用它。

从类型 T 中选择出属性 K,构造成一个新的类型

例如:

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

type TodoPreview = MyPick<Todo, 'title' | 'completed'>

const todo: TodoPreview = {
    title: 'Clean room',
    completed: false,
}
English - Subject

Implement the built-in Pick<T, K> generic without using it.

Constructs a type by picking the set of properties K from T

For example:

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

type TodoPreview = MyPick<Todo, 'title' | 'completed'>

const todo: TodoPreview = {
    title: 'Clean room',
    completed: false,
}

答案

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

在线测试

标签:Typescript,string,title,completed,体操,Pick,type,TodoPreview
From: https://www.cnblogs.com/laggage/p/type-challenge-pick.html

相关文章