使用字符串值创建枚举 [英] Create an enum with string values

查看:4
本文介绍了使用字符串值创建枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可用于创建enumIn TypeScrip:

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

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

e.hello;
e.world;

如何使用字符串值创建enum

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

推荐答案

类型脚本2.4

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

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

🌹

文字1.8

从TypeScrip1.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

旧版支持

打印脚本中的枚举是基于数字的。

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

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); 

这篇关于使用字符串值创建枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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