且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法将字符串值分配给打字稿枚举(初始化程序类型的字符串不可分配给变量类型)

更新时间:2022-11-30 19:07:25

您可以使用索引表达式来获取枚举的值:

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