我已经完成了以下片段来支持带有字符串的枚举
enum Color {
red = <any>"red", green = <any>"green", Blue = <any>"blue"
}
有什么方法以及为什么我们需要它?
最佳答案
What is the means
Typescript 枚举只是数字
。因此,如果你分配一个字符串,编译器会提示。
enum Color {
red = "red" // error `string` is not assignable to color
}
但是通过使用any
,您是在告诉编译器嘘……我更清楚。 More on this 。
注意:如果您这样做,您可能需要再次 shhhhh 编译器,例如:
enum Color {
red = <any>"red" // shhhh
}
var foo = Color.red; // okay
foo = 123; // okay: TypeScript still thinks red is a number
foo = "red"; // Error
foo = <any>"red"; // shhhhh
断言到底是什么
基于替代字符串的枚举
why we need it
如果您想要基于字符串的枚举。我个人现在使用这种模式:https://basarat.gitbooks.io/typescript/content/docs/tips/stringEnums.html
Typescript 1.8 将会提供一流的支持,例如
type Foo = "a" | "b";
关于typescript - 枚举中的 <any> 以及 typescript 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33684133/