TypeScript

Discriminated Unions(a.k.a tagged/disjointed/sum type)

大量的库使用了该方式,来进行类型区分。由于目前 ts 是 untagged 的,所以需要借助值空间来实现 tag,通过值空间的约束,继而让类型空间实现收缩。
https://thoughtbot.com/blog/the-case-for-discriminated-union-types-with-typescript
https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions
通过在类型上添加 tag 属性,并在值空间中,真实定义对应的属性,以获得守卫。这样可以通过同一个 tag 属性,来进行 union 的收缩。

  1. type Official = {
  2. __typename: 'Official',
  3. name: string,
  4. age: number,
  5. }
  6. type Monarch = {
  7. __typename: 'Monarch',
  8. name: string,
  9. title: string,
  10. }
  11. type Boss = Official | Monarch;
  12. const bossDescription = (boss: Boss): string => {
  13. if (boss.__typename === 'Official') {
  14. return `${boss.name}, ${boss.age} years old`;
  15. }
  16. return `${boss.title}, ${boss.name}`;
  17. }