【问题标题】:What does it mean for a type to distribute over unions?一个类型分布在联合上意味着什么?
【发布时间】:2020-09-16 22:57:51
【问题描述】:

我正在阅读一篇文章:"Unionize and Objectify: A Trick for Applying Conditional Types to Objects"

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

  • 他们分配给工会。
  • 它们使您能够使用 infer 关键字。

在一般情况下以及在这种情况下,“通过联合分配”是什么意思?

【问题讨论】:

标签: typescript types theory union-types conditional-types


【解决方案1】:

distributive 一词是指联合类型在进行类型级别操作时应如何处理(例如 keyof 或映射类型)。

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

让我们举个例子。

type Fruit =
  | { species: 'banana', curvature: number }
  | { species: 'apple', color: string }

假设出于某种原因,您想知道Fruit 上可能存在的所有可能键。

非分配性

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

type KeyOfFruit = keyof Fruit; // "species"

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

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

keyof ({ species: 'banana', curvature: number } | { species: 'apple', color: string })

分布式

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

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

type KeyOfFruit = DistributedKeyOf<Fruit>; // "species" | "curvature" | "color"

在这种情况下,TypeScript 将keyof 应用于联合的每个成员,并对结果求和。

keyof { species: 'banana', curvature: number } | keyof { species: 'apple', color: string }
猜你喜欢
  • 2013-01-16
  • 2021-09-24
  • 1970-01-01
  • 2014-08-01
  • 2010-09-14
  • 2021-11-04
  • 1970-01-01
  • 2012-01-20
相关资源
最近更新 更多