326

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

28 に答える 28

490

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); 
于 2013-03-19T05:04:09.130 に答える
117

TypeScriptの最新バージョン(1.0RC)では、次のような列挙型を使用できます。

enum States {
    New,
    Active,
    Disabled
} 

// this will show message '0' which is number representation of enum member
alert(States.Active); 

// this will show message 'Disabled' as string representation of enum member
alert(States[States.Disabled]);

アップデート1

文字列値から列挙型メンバーの数値を取得するには、次を使用できます。

var str = "Active";
// this will show message '1'
alert(States[str]);

アップデート2

最新のTypeScript2.4では、次のような文字列列挙型が導入されました。

enum ActionType {
    AddUser = "ADD_USER",
    DeleteUser = "DELETE_USER",
    RenameUser = "RENAME_USER",

    // Aliases
    RemoveUser = DeleteUser,
}

TypeScript 2.4の詳細については、MSDNのブログを参照してください。

于 2014-02-27T14:47:18.453 に答える
84

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

于 2016-02-07T18:29:58.357 に答える
40

TypeScript 0.9.0.1では、コンパイラエラーが発生しますが、コンパイラはtsファイルをjsファイルにコンパイルできます。コードは期待どおりに機能し、VisualStudio2012はコードの自動補完をサポートできます。

アップデート :

構文では、TypeScriptでは文字列値を使用して列挙型を作成することはできませんが、コンパイラをハックすることはできます:p

enum Link
{
    LEARN   =   <any>'/Tutorial',
    PLAY    =   <any>'/Playground',
    GET_IT  =   <any>'/#Download',
    RUN_IT  =   <any>'/Samples',
    JOIN_IN =   <any>'/#Community'
}

alert('Link.LEARN:    '                     + Link.LEARN);
alert('Link.PLAY:    '                      + Link.PLAY);
alert('Link.GET_IT:    '                    + Link.GET_IT);
alert('Link[\'/Samples\']:    Link.'        + Link['/Samples']);
alert('Link[\'/#Community\']    Link.'      + Link['/#Community']);

遊び場

于 2013-07-24T16:18:39.007 に答える
25

TypeScript 2.1 +

TypeScript 2.1で導入されたルックアップタイプにより、文字列列挙型をシミュレートするための別のパターンが可能になります。

// String enums in TypeScript 2.1
const EntityType = {
    Foo: 'Foo' as 'Foo',
    Bar: 'Bar' as 'Bar'
};

function doIt(entity: keyof typeof EntityType) {
    // ...
}

EntityType.Foo          // 'Foo'
doIt(EntityType.Foo);   // 
doIt(EntityType.Bar);   // 
doIt('Foo');            // 
doIt('Bar');            // 
doIt('Baz');            //  

TypeScript 2.4 +

バージョン2.4では、TypeScriptは文字列列挙型のネイティブサポートを導入したため、上記のソリューションは必要ありません。TSドキュメントから:

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}
于 2017-01-13T09:53:06.373 に答える
19

列挙型の文字列にアクセスするネイティブな方法を使用しないのはなぜですか。

enum e {
  WHY,
  NOT,
  USE,
  NATIVE
}

e[e.WHY] // this returns string 'WHY'
于 2015-04-17T11:47:47.760 に答える
17

最新のTypeScriptでは文字列列挙型を使用できます。

enum e
{
    hello = <any>"hello",
    world = <any>"world"
};

ソース:https ://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/


更新-2016

最近Reactに使用する文字列のセットを作成するもう少し堅牢な方法は、次のようになります。

export class Messages
{
    static CouldNotValidateRequest: string = 'There was an error validating the request';
    static PasswordMustNotBeBlank: string = 'Password must not be blank';   
}

import {Messages as msg} from '../core/messages';
console.log(msg.PasswordMustNotBeBlank);
于 2015-12-11T10:35:18.193 に答える
10

TypeScript 2.0を使用して、継承を可能にするかなりクリーンなソリューションを次に示します。以前のバージョンではこれを試しませんでした。

ボーナス:値はどのタイプでもかまいません!

export class Enum<T> {
  public constructor(public readonly value: T) {}
  public toString() {
    return this.value.toString();
  }
}

export class PrimaryColor extends Enum<string> {
  public static readonly Red = new Enum('#FF0000');
  public static readonly Green = new Enum('#00FF00');
  public static readonly Blue = new Enum('#0000FF');
}

export class Color extends PrimaryColor {
  public static readonly White = new Enum('#FFFFFF');
  public static readonly Black = new Enum('#000000');
}

// Usage:

console.log(PrimaryColor.Red);
// Output: Enum { value: '#FF0000' }
console.log(Color.Red); // inherited!
// Output: Enum { value: '#FF0000' }
console.log(Color.Red.value); // we have to call .value to get the value.
// Output: #FF0000
console.log(Color.Red.toString()); // toString() works too.
// Output: #FF0000

class Thing {
  color: Color;
}

let thing: Thing = {
  color: Color.Red,
};

switch (thing.color) {
  case Color.Red: // ...
  case Color.White: // ...
}
于 2016-10-14T02:39:58.840 に答える
9

更新:TypeScript 3.4

あなたは単に使用することができますas const

const AwesomeType = {
   Foo: "foo",
   Bar: "bar"
} as const;

TypeScript 2.1

これもこの方法で行うことができます。それが誰かを助けることを願っています。

const AwesomeType = {
    Foo: "foo" as "foo",
    Bar: "bar" as "bar"
};

type AwesomeType = (typeof AwesomeType)[keyof typeof AwesomeType];

console.log(AwesomeType.Bar); // returns bar
console.log(AwesomeType.Foo); // returns foo

function doSth(awesometype: AwesomeType) {
    console.log(awesometype);
}

doSth("foo") // return foo
doSth("bar") // returns bar
doSth(AwesomeType.Bar) // returns bar
doSth(AwesomeType.Foo) // returns foo
doSth('error') // does not compile
于 2017-03-15T20:32:36.800 に答える
7

これは私のために働きます:

class MyClass {
    static MyEnum: { Value1; Value2; Value3; }
    = {
        Value1: "Value1",
        Value2: "Value2",
        Value3: "Value3"
    };
}

また

module MyModule {
    export var MyEnum: { Value1; Value2; Value3; }
    = {
        Value1: "Value1",
        Value2: "Value2",
        Value3: "Value3"
    };
}

8)

更新:これを投稿した直後に私は別の方法を発見しましたが、更新を投稿するのを忘れました(ただし、誰かがすでに上記で言及しました):

enum MyEnum {
    value1 = <any>"value1 ", 
    value2 = <any>"value2 ", 
    value3 = <any>"value3 " 
}
于 2013-07-18T17:02:08.520 に答える
7

これへのハッキーな方法は:-

CallStatus.ts

enum Status
{
    PENDING_SCHEDULING,
    SCHEDULED,
    CANCELLED,
    COMPLETED,
    IN_PROGRESS,
    FAILED,
    POSTPONED
}

export = Status

Utils.ts

static getEnumString(enum:any, key:any):string
{
    return enum[enum[key]];
}

使い方

Utils.getEnumString(Status, Status.COMPLETED); // = "COMPLETED"
于 2014-01-23T11:52:25.823 に答える
5

答えはたくさんありますが、完全な解決策は見当たりません。受け入れられた答えの問題は、同様にenum { this, one }、あなたがたまたま使用している文字列値を多くのファイルに分散させることです。「更新」もあまり好きではありません。複雑で、タイプも活用していません。Michael Bromleyの答えが最も正しいと思いますが、そのインターフェイスは少し面倒で、型を使用することもできます。

私はTypeScript2.0を使用しています。+...これが私がすることです

export type Greeting = "hello" | "world";
export const Greeting : { hello: Greeting , world: Greeting } = {
    hello: "hello",
    world: "world"
};

次に、次のように使用します。

let greet: Greeting = Greeting.hello

また、便利なIDEを使用すると、タイプ/ホバーオーバーの情報が大幅に向上します。欠点は、文字列を2回書き込む必要があることですが、少なくとも2か所にしかありません。

于 2017-03-07T13:38:05.787 に答える
4

インターフェイスを宣言し、そのタイプの変数を使用して列挙型にアクセスします。TypeScriptは列挙型で何かが変更された場合に文句を言うので、インターフェイスと列挙型の同期を維持することは実際には簡単です。

エラーTS2345:タイプ'typeofEAbFlagEnum'の引数をタイプ'IAbFlagEnum'のパラメーターに割り当てることができません。プロパティ「移動」がタイプ「typeofEAbFlagEnum」にありません。

この方法の利点は、さまざまな状況で列挙型(インターフェース)を使用するために型キャストが不要であるため、スイッチ/ケースなど、より多くのタイプの状況がサポートされることです。

// Declare a TypeScript enum using unique string 
//  (per hack mentioned by zjc0816)

enum EAbFlagEnum {
  None      = <any> "none",
  Select    = <any> "sel",
  Move      = <any> "mov",
  Edit      = <any> "edit",
  Sort      = <any> "sort",
  Clone     = <any> "clone"
}

// Create an interface that shadows the enum
//   and asserts that members are a type of any

interface IAbFlagEnum {
    None:   any;
    Select: any;
    Move:   any;
    Edit:   any;
    Sort:   any;
    Clone:  any;
}

// Export a variable of type interface that points to the enum

export var AbFlagEnum: IAbFlagEnum = EAbFlagEnum;

列挙型ではなく変数を使用すると、目的の結果が得られます。

var strVal: string = AbFlagEnum.Edit;

switch (strVal) {
  case AbFlagEnum.Edit:
    break;
  case AbFlagEnum.Move:
    break;
  case AbFlagEnum.Clone
}

フラグは私にとってもう1つの必需品だったので、この例に追加し、テストを含むNPMモジュールを作成しました。

https://github.com/djabraham/ts-enum-tools

于 2015-11-17T03:30:23.900 に答える
2

typescript @ nextで利用可能なカスタムトランスフォーマー(https://github.com/Microsoft/TypeScript/pull/13940)を使用すると、文字列リテラル型からの文字列値を使用して列挙型オブジェクトを作成できます。

私のnpmパッケージts-transformer-enumerateを調べてください。

使用例:

// The signature of `enumerate` here is `function enumerate<T extends string>(): { [K in T]: K };`
import { enumerate } from 'ts-transformer-enumerate';

type Colors = 'green' | 'yellow' | 'red';
const Colors = enumerate<Colors>();

console.log(Colors.green); // 'green'
console.log(Colors.yellow); // 'yellow'
console.log(Colors.red); // 'red'
于 2017-04-23T15:19:06.220 に答える
2

TypeScript <2.4

/** Utility function to create a K:V from a list of strings */
function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
  return o.reduce((res, key) => {
    res[key] = key;
    return res;
  }, Object.create(null));
}

/**
  * Sample create a string enum
  */

/** Create a K:V */
const Direction = strEnum([
  'North',
  'South',
  'East',
  'West'
])
/** Create a Type */
type Direction = keyof typeof Direction;

/** 
  * Sample using a string enum
  */
let sample: Direction;

sample = Direction.North; // Okay
sample = 'North'; // Okay
sample = 'AnythingElse'; // ERROR!

https://basarat.gitbooks.io/typescript/docs/types/literal-types.htmlから

ソースリンクへは、文字列リテラル型を実現するためのより簡単な方法を見つけることができます

于 2017-09-08T08:31:51.137 に答える
1

最近TypeScript1.0.1でこの問題に直面し、次のように解決しました。

enum IEvents {
        /** A click on a product or product link for one or more products. */
        CLICK,
        /** A view of product details. */
        DETAIL,
        /** Adding one or more products to a shopping cart. */
        ADD,
        /** Remove one or more products from a shopping cart. */
        REMOVE,
        /** Initiating the checkout process for one or more products. */
        CHECKOUT,
        /** Sending the option value for a given checkout step. */
        CHECKOUT_OPTION,
        /** The sale of one or more products. */
        PURCHASE,
        /** The refund of one or more products. */
        REFUND,
        /** A click on an internal promotion. */
        PROMO_CLICK
}

var Events = [
        'click',
        'detail',
        'add',
        'remove',
        'checkout',
        'checkout_option',
        'purchase',
        'refund',
        'promo_click'
];

function stuff(event: IEvents):boolean {
        // event can now be only IEvents constants
        Events[event]; // event is actually a number that matches the index of the array
}
// stuff('click') won't work, it needs to be called using stuff(IEvents.CLICK)
于 2014-11-05T23:38:05.590 に答える
1

@basaratの答えは素晴らしかった。これは単純化されていますが、使用できる少し拡張された例です。

export type TMyEnumType = 'value1'|'value2';

export class MyEnumType {
    static VALUE1: TMyEnumType = 'value1';
    static VALUE2: TMyEnumType = 'value2';
}

console.log(MyEnumType.VALUE1); // 'value1'

const variable = MyEnumType.VALUE2; // it has the string value 'value2'

switch (variable) {
    case MyEnumType.VALUE1:
        // code...

    case MyEnumType.VALUE2:
        // code...
}
于 2017-03-09T12:01:24.600 に答える
1

私は同じ質問をし、うまく機能する関数を思いついた:

  • 各エントリのキーと値は文字列であり、同一です。
  • 各エントリの値はキーから取得されます。(つまり、文字列値を持つ通常の列挙型とは異なり、「自分自身を繰り返さないでください」)
  • TypeScriptタイプは、本格的で正しいものです。(タイプミスの防止)
  • TSにオプションをオートコンプリートさせる簡単な方法が残っています。(例:入力するMyEnum.と、すぐに利用可能なオプションが表示されます)
  • そして、他のいくつかの利点。(回答の下部を参照)

ユーティリティ関数:

export function createStringEnum<T extends {[key: string]: 1}>(keysObj: T) {
    const optionsObj = {} as {
        [K in keyof T]: keyof T
        // alternative; gives narrower type for MyEnum.XXX
        //[K in keyof T]: K
    };
    const keys = Object.keys(keysObj) as Array<keyof T>;
    const values = keys; // could also check for string value-overrides on keysObj
    for (const key of keys) {
        optionsObj[key] = key;
    }
    return [optionsObj, values] as const;
}

使用法:

// if the "Fruit_values" var isn't useful to you, just omit it
export const [Fruit, Fruit_values] = createStringEnum({
    apple: 1,
    pear: 1,
});
export type Fruit = keyof typeof Fruit; // "apple" | "pear"
//export type Fruit = typeof Fruit_values[number]; // alternative

// correct usage (with correct types)
let fruit1 = Fruit.apple; // fruit1 == "apple"
fruit1 = Fruit.pear; // assigning a new fruit also works
let fruit2 = Fruit_values[0]; // fruit2 == "apple"

// incorrect usage (should error)
let fruit3 = Fruit.tire; // errors
let fruit4: Fruit = "mirror"; // errors

今、誰かが尋ねるかもしれません、この「文字列ベースの列挙型」を単に使用することに対する利点は何ですか?

type Fruit = "apple" | "pear";

いくつかの利点があります。

  1. オートコンプリートは少し良いです(imo)。たとえば、と入力するlet fruit = Fruit.と、Typescriptは使用可能なオプションの正確なセットをすぐに一覧表示します。文字列リテラルでは、タイプを明示的に定義する必要があります。let fruit: Fruit = 、その後ctrl+spaceを押します。(それでも、関連のないオートコンプリートオプションが有効なオプションの下に表示されます)
  2. オプションのTSDocメタデータ/説明はフィールドに引き継がれMyEnum.XXXます!これは、さまざまなオプションに関する追加情報を提供するのに役立ちます。例えば:
  3. オプションのリストには、実行時にアクセスできます(たとえばFruit_values、またはを使用して手動でObject.values(Fruit))。このtype Fruit = ...アプローチでは、これを行うための組み込みの方法がなく、多くのユースケースが削減されます。(たとえば、json-schemasを構築するためにランタイム値を使用します)
于 2021-06-26T15:09:57.813 に答える
1

Typescriptの文字列列挙型:

文字列列挙型も同様の概念ですが、以下に示すように、実行時の微妙な違いがいくつかあります。文字列列挙型では、各メンバーは、文字列リテラルまたは別の文字列列挙型メンバーで定数初期化する必要があります。

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}

文字列列挙型には自動インクリメントの動作はありませんが、文字列列挙型には、適切に「シリアル化」されるという利点があります。言い換えると、デバッグ中に数値列挙型の実行時値を読み取る必要がある場合、値は不透明であることがよくあります。それ自体では有用な意味を伝えません(ただし、逆マッピングが役立つことがよくあります)。文字列列挙型を使用すると、列挙型メンバー自体の名前に関係なく、コードの実行時に意味のある読みやすい値を提供します。参考リンクは以下の通りです。

ここにリンクの説明を入力してください

于 2021-06-30T09:35:40.040 に答える
0

TypeScript 0.9.0.1

enum e{
    hello = 1,
    somestr = 'world'
};

alert(e[1] + ' ' + e.somestr);

TypeScriptプレイグラウンド

于 2013-07-03T19:54:53.600 に答える
0

これを試してみるべきだと思います。この場合、変数の値は変更されず、列挙型のように機能します。クラスのように使用することも機能します。唯一の欠点は、静的変数の値を誤って変更できることです。列挙型は必要ありません。

namespace portal {

export namespace storageNames {

    export const appRegistration = 'appRegistration';
    export const accessToken = 'access_token';

  }
}
于 2015-08-20T18:04:41.550 に答える
0

私は以下のようにTypeScript1.5で試しましたが、うまくいきました

module App.Constants {
   export enum e{
        Hello= ("Hello") as any,
World= ("World") as any
    }
}
于 2015-12-04T20:35:47.213 に答える
0
export enum PaymentType {
                Cash = 1,
                Credit = 2
            }
var paymentType = PaymentType[PaymentType.Cash];
于 2016-03-02T23:53:32.487 に答える
0
//to access the enum with its string value you can convert it to object 
//then you can convert enum to object with proberty 
//for Example :

enum days { "one" =3, "tow", "Three" }

let _days: any = days;

if (_days.one == days.one)
{ 
    alert(_days.one + ' | ' + _days[4]);
}
于 2017-06-13T14:47:35.483 に答える
0

少しjs-ハッキーですが動作します:e[String(e.hello)]

于 2017-07-02T02:06:29.437 に答える
0

必要なものが主に簡単なデバッグ(かなりタイプチェック付き)であり、列挙型に特別な値を指定する必要がない場合、これは私が行っていることです:

export type Enum = { [index: number]: string } & { [key: string]: number } | Object;

/**
 * inplace update
 * */
export function enum_only_string<E extends Enum>(e: E) {
  Object.keys(e)
    .filter(i => Number.isFinite(+i))
    .forEach(i => {
      const s = e[i];
      e[s] = s;
      delete e[i];
    });
}

enum AuthType {
  phone, email, sms, password
}
enum_only_string(AuthType);

レガシーコード/データストレージをサポートしたい場合は、数字キーを保持することができます。

このようにして、値を2回入力することを回避できます。

于 2017-07-04T13:08:55.787 に答える
0

文字列を含む非常に、非常に、非常に単純な列挙型(TypeScript 2.4)

import * from '../mylib'

export enum MESSAGES {
    ERROR_CHART_UNKNOWN,
    ERROR_2
}

export class Messages {
    public static get(id : MESSAGES){
        let message = ""
        switch (id) {
            case MESSAGES.ERROR_CHART_UNKNOWN :
                message = "The chart does not exist."
                break;
            case MESSAGES.ERROR_2 :
                message = "example."
                break;
        }
        return message
    }
}

function log(messageName:MESSAGES){
    console.log(Messages.get(messageName))
}
于 2017-08-03T11:15:44.627 に答える
0

私はtypescript列挙型(v2.5)で説明を実装する方法を探していましたが、このパターンは私のために機能しました:

export enum PriceTypes {
    Undefined = 0,
    UndefinedDescription = 'Undefined' as any,
    UserEntered = 1,
    UserEnteredDescription = 'User Entered' as any,
    GeneratedFromTrade = 2,
    GeneratedFromTradeDescription = 'Generated From Trade' as any,
    GeneratedFromFreeze = 3,
    GeneratedFromFreezeDescription = 'Generated Rom Freeze' as any
}

..。

    GetDescription(e: any, id: number): string {
        return e[e[id].toString() + "Description"];
    }
    getPriceTypeDescription(price: IPricePoint): string {
        return this.GetDescription(PriceTypes, price.priceType);
    }
于 2018-06-26T13:52:16.177 に答える