文字列値を持つ列挙型を作成する 質問する

文字列値を持つ列挙型を作成する 質問する

次のコードを使用して、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 
};

ベストアンサー1

タイプスクリプト 2.4

文字列列挙型が追加されたため、コードは問題なく動作します。

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

��

タイプスクリプト 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#文字列リテラルタイプ

レガシーサポート

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

おすすめ記事