我想要严格类型化的可变对象,就像 Haxe 枚举一样。
enum Color {
Red;
Rgb(r:Int, g:Int, b:Int);
Rgba(r:Int, g:Int, b:Int, a:Int);
}
我希望仅当我的对象是 Rgba
时才能够访问 a
参数,如果我的对象是红色
。
我并不关心在 typescript 中是否使用enum
关键字。
有什么方法可以在 Typescript 中实现这一点吗?
最佳答案
从版本 2.0 开始,Typescript supports tagged unions在某种程度上。一般语法为
type MyType = A | B | C …;
哪里A
, B
和C
是接口(interface)。一个MyType
对象可以是这些类型中的任何一种,不能是其他类型。该公告给出了一个简单的例子:
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
)。
关于带参数的 typescript 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40656955/