无法将字符串值分配给打字稿枚举(初始化程序类型的字符串不可分配给变量类型) [英] Cannot assign a string value to typescript enum (Initializer type string not assignable to variable type)

查看:111
本文介绍了无法将字符串值分配给打字稿枚举(初始化程序类型的字符串不可分配给变量类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从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

这篇关于无法将字符串值分配给打字稿枚举(初始化程序类型的字符串不可分配给变量类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆