无法将字符串值分配给打字稿枚举(初始化程序类型的字符串不可分配给变量类型)
问题描述:
从TypeScript 2.4开始,似乎字符串枚举是一项功能。
It seems that from TypeScript 2.4 onwards String Enums are a feature.
但是以下操作无效:
enum Foo {
A = "A",
B = "B"
}
var foo : Foo = "A";
初始化程序类型字符串不能分配给变量类型Foo
Initializer type string not assignable to variable type Foo
字符串文字有效:
type Foo = "A" | "B";
但是如果我想要使用怎么办枚举
?
答
您可以使用索引表达式来获取枚举的值:
You can use an index expression to get the value of the enum:
enum Foo {
A = "A",
B = "BB"
}
var foo : Foo = Foo["A"];
var fooB : Foo = Foo["B"];
请注意,键将是成员的名称而不是值。
Note that the key will be the name of the member not the value.
您也可以使用类型断言,但如果分配了错误的值,则不会出错:
You could also use a type assertion, but you will not get errors if you assign a wrong value:
var foo : Foo = "A" as Foo;
var foo : Foo = "D" as Foo; // No error