为了账号安全,请及时绑定邮箱和手机立即绑定

用字符串值创建一个枚举

用字符串值创建一个枚举

iOS
偶然的你 2019-10-25 13:15:37
以下代码可用于enum在TypeScript中创建一个:enum e {    hello = 1,    world = 2};可以通过以下方式访问这些值:e.hello;e.world;如何创建enum带有字符串值的?enum e {    hello = "hello", // error: cannot convert string to e    world = "world"  // error };
查看完整描述

3 回答

?
森林海

TA贡献2011条经验 获得超2个赞

TypeScript 2.4+


现在,您可以直接将字符串值分配给枚举成员:


enum Season {

    Winter = "winter",

    Spring = "spring",

    Summer = "summer",

    Fall = "fall"

}

有关更多信息,请参见#15486。


TypeScript 1.8以上


在TypeScript 1.8+中,您可以创建一个字符串文字类型来定义该类型,并为值列表创建一个名称相同的对象。它模仿字符串枚举的预期行为。


这是一个例子:


type MyStringEnum = "member1" | "member2";


const MyStringEnum = {

    Member1: "member1" as MyStringEnum,

    Member2: "member2" as MyStringEnum

};

它将像字符串枚举一样工作:


// implicit typing example

let myVariable = MyStringEnum.Member1; // ok

myVariable = "member2";                // ok

myVariable = "some other value";       // error, desired


// explict typing example

let myExplicitlyTypedVariable: MyStringEnum;

myExplicitlyTypedVariable = MyStringEnum.Member1; // ok

myExplicitlyTypedVariable = "member2";            // ok

myExplicitlyTypedVariable = "some other value";   // error, desired

确保键入对象中的所有字符串!如果不这样做,则在上面的第一个示例中,该变量将不会隐式键入为MyStringEnum。


查看完整回答
反对 回复 2019-10-25
  • 3 回答
  • 0 关注
  • 617 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信