typescript - 使用字符串值创建枚举

标签 typescript

以下代码可用于在 TypeScript 中创建 enum:

enum e {
    hello = 1,
    world = 2
};

并且可以通过以下方式访问这些值:

e.hello;
e.world;

如何创建一个包含字符串值的enum

enum e {
    hello = "hello", // error: cannot convert string to e
    world = "world"  // error 
};

最佳答案

typescript 2.4

现在有字符串枚举,因此您的代码可以正常工作:

enum E {
    hello = "hello",
    world = "world"
};

🌹

typescript 1.8

从 TypeScript 1.8 开始,您可以使用字符串文字类型为命名字符串值(枚举的部分用途)提供可靠且安全的体验。

type Options = "hello" | "world";
var foo: Options;
foo = "hello"; // Okay 
foo = "asdf"; // Error!

更多:https://www.typescriptlang.org/docs/handbook/advanced-types.html#string-literal-types

旧版支持

TypeScript 中的枚举是基于数字的。

不过,您可以使用具有静态成员的类:

class E
{
    static hello = "hello";
    static world = "world"; 
}

你也可以直接说:

var E = {
    hello: "hello",
    world: "world"
}

更新: 基于能够执行类似 var test:E = E.hello; 的要求,以下满足此要求:

class E
{
    // boilerplate 
    constructor(public value:string){    
    }

    toString(){
        return this.value;
    }

    // values 
    static hello = new E("hello");
    static world = new E("world");
}

// Sample usage: 
var first:E = E.hello;
var second:E = E.world;
var third:E = E.hello;

console.log("First value is: "+ first);
console.log(first===third); 

关于typescript - 使用字符串值创建枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15490560/

相关文章:

angular - 使用 angular2 发送身份验证凭据

javascript - 使用 Typescript 将 prop 渲染为字符串或组件

typescript - client.matchAll() 在 typescript 中给出错误 "Cannot find name ' client'"

angular - 我得到 "Http failure response for (unknown url): 0 Unknown Error"而不是 Angular 中的实际错误消息

typescript - 检查后未定义?

angular - 在 Angular 5 应用程序中导入第三方 js 库 cq-prolyfill 的正确方法

angular - 运行 Angular 编译器-cli (ngc);找不到模块 '@angular/core'

typescript - 如何在 Ionic 4 应用程序中嵌入 Youtube 视频

带有 system.js 模块的 TypeScript 在节点错误中运行

javascript - 当数据类属性更改时重新渲染 React 组件