2016-11-17 92 views
2

我想严格键入可变对象,就像Haxe枚举一样。带参数的Typescript枚举

In haxe, you can do

enum Color { 
    Red; 
    Rgb(r:Int, g:Int, b:Int); 
    Rgba(r:Int, g:Int, b:Int, a:Int); 
} 

我希望能够访问a参数只有当我的对象是一个Rgba,如果我的对象是Red我不能访问任何参数。

我并不在乎在打字稿中是否使用enum关键字。

有没有办法在Typescript中实现这一点?

+1

你的意思是“可变的”吗?我不认识Haxe,但枚举在其他语言中几乎是普遍的*不可变的*。无论如何,你所描述的可能被称为Haxe中的枚举,但通常以不同的名字来命名,例如[* sum type *或* tagged union *](https://en.wikipedia.org/wiki/Tagged_union ),其中枚举是一个特例。 –

+0

你会如何使用它? –

+0

@KonradRudolph我真的很喜欢那个'taggued union'。我怎样才能以类型安全的方式在打字稿中使用它? – blue112

回答

2

至于版本2.0,Typescript supports tagged unions在一定程度上。一般语法是

type MyType = A | B | C …; 

ABC是接口。对象然后可以是这些类型中的任何一种,而不是其他类型。公告给出了一个简单的例子:

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)手工检查,如果这些联合类型的类型安全。