typescript 实施提货类型

b5buobof  于 2023-02-13  发布在  TypeScript
关注(0)|答案(1)|浏览(140)

在尝试实现Pick时,我不确定为什么WrongPick类型会给|带来糟糕的结果。

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

type WrongPick<T, K> =  K extends keyof T ? {[P in K]: T[P]} : never

type wrong_result = WrongPick<Todo, 'title' | 'completed'>
// expected: { title: string ; completed: boolean }
// actual: { title: string } | { completed: boolean }

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

type correct_result = CorrectPick<Todo, 'title' | 'completed'>
// expected: { title: string ; completed: boolean }
// actual: { title: string ; completed: boolean }

打字机Playground

wn9m85ua

wn9m85ua1#

由于分布式条件类型,WrongPick<Todo, "title" | "completed">实际上扩展为

("title" extends keyof T ? { [P in "title"]: Todo[P] } : never) | ("completed" extends keyof T ? { [P in "completed"]: Todo[P] } : never)

其简化为

{ title: string } | { completed: boolean }

如上述文档链接所述,您可以通过将两端 Package 在元组中来"关闭它":

type WrongPick<T, K> =  [K] extends [keyof T] ? { [P in K]: T[P] } : never

Playground

相关问题