类型通过联合分配意味着什么?

Iva*_*lev 6 theory types typescript union-types conditional-types

我正在阅读一篇文章:“Unionize 和 Objectify:将条件类型应用于对象的技巧”

在 TypeScript 中,我们最强大的工具是条件类型。这是因为他们有两个独特的能力:

  • 他们通过工会进行分配。
  • 它们使您能够使用 infer 关键字。

在一般情况下以及在这种情况下,“在工会上分配”意味着什么?

Kar*_*ski 17

术语“分布式”是指在进行类型级操作(例如keyof或 映射类型)时应如何处理联合类型。

  • 非分配(默认)操作应用于联合的每个成员上存在的属性。
  • 分配运算分别应用于联盟的所有成员。

让我们举个例子。

type Fruit =
  | { species: 'banana', curvature: number }
  | { species: 'apple', color: string }
Run Code Online (Sandbox Code Playgroud)

让我们假设,由于某种原因,您想知道Fruit.

非分配性

您的直觉可能会告诉您这样做:

type KeyOfFruit = keyof Fruit; // "species"
Run Code Online (Sandbox Code Playgroud)

但是,这只会为您提供联合体每个成员都存在的属性。在我们的示例中,species是所有人共享的唯一公共财产Fruit

keyof这与应用于两种类型的并集相同。

keyof ({ species: 'banana', curvature: number } | { species: 'apple', color: string })
Run Code Online (Sandbox Code Playgroud)

分配性

通过分发,操作不仅仅针对公共属性执行。相反,它是分别对工会的每个成员进行的。然后将结果相加。

type DistributedKeyOf<T> =
  T extends any
    ? keyof T
    : never

type KeyOfFruit = DistributedKeyOf<Fruit>; // "species" | "curvature" | "color"
Run Code Online (Sandbox Code Playgroud)

在本例中,TypeScript 应用于keyof联合的每个成员,并对结果求和。

keyof { species: 'banana', curvature: number } | keyof { species: 'apple', color: string }
Run Code Online (Sandbox Code Playgroud)

  • FWIW 人们可能想查看[分布式条件类型的手册文档](https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types) (2认同)