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 的收缩。
type Official = {__typename: 'Official',name: string,age: number,}type Monarch = {__typename: 'Monarch',name: string,title: string,}type Boss = Official | Monarch;const bossDescription = (boss: Boss): string => {if (boss.__typename === 'Official') {return `${boss.name}, ${boss.age} years old`;}return `${boss.title}, ${boss.name}`;}
