TypeScript$Type-Value-UnionAndIntersection

58 阅读1分钟

TypeScript$Type-Value-UnionAndIntersection

0. Value and Type

我们把变量比作人。Value 指的是人这个实体,Type 则表示能力。

当我们描述变量时,我们说“会开车的张三”,“会前端的李四”,“会全栈的王五”。

1. AND &

有时候我们“既要又要”:“会前端且会后端的人 => 会全栈的人”。这时,& 来了。

type FrontEnd = { frontEnd: number }
type BackEnd = { backEnd: number }
type FullStack = FrontEnd & BackEnd

这里的 FullStack 即有 frontEnd 属性,又有 backEnd 属性。

2. OR |

有时候我们“有一个就行”:“会 Vue 或者 React 的人”。这时,| 来了。

type Vue = { vue: number }
type React = { react: number }
type WebFramework = Vue | React

这里的 WebFramework 可能有 vue 属性,也可能有 react 属性,但至少有一个。

3. AND or OR

假如我们想要挑选顶尖人才:必须满足很多更能力才行。那么使用 AND &

假如我们想要选个凑合临时工:只要能有一些能力中的一个就行了。那么使用 OR |

4. Venn Diagram

维恩图能比较好的描述 AND 和 OR 的关系。

下图中 Red∩Yellow 表示 Red 和 Yellow 的交集,即 AND。Red 和 Yellow 包含的所有内容是并集,即 OR。

RedYellow.svg

Links

UnionTypes

IntersectionTypes