至于版本2.0,Typescript supports tagged unions在一定程度上。一般语法是
type MyType = A | B | C …;
凡A
,B
和C
是接口。对象然后可以是这些类型中的任何一种,而不是其他类型。公告给出了一个简单的例子:
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
interface Circle {
kind: "circle";
radius: number;
}
type Shape = Square | Rectangle | Circle;
function area(s: Shape) {
// In the following switch statement, the type of s is narrowed in each case clause
// according to the value of the discriminant property, thus allowing the other properties
// of that variant to be accessed without a type assertion.
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.width * s.height;
case "circle": return Math.PI * s.radius * s.radius;
}
}
然而,需要看守,并用所谓的“判别属性类型后卫”作为示例显示(检查s.kind
)手工检查,如果这些联合类型的类型安全。
你的意思是“可变的”吗?我不认识Haxe,但枚举在其他语言中几乎是普遍的*不可变的*。无论如何,你所描述的可能被称为Haxe中的枚举,但通常以不同的名字来命名,例如[* sum type *或* tagged union *](https://en.wikipedia.org/wiki/Tagged_union ),其中枚举是一个特例。 –
你会如何使用它? –
@KonradRudolph我真的很喜欢那个'taggued union'。我怎样才能以类型安全的方式在打字稿中使用它? – blue112