문자열 값으로 열거 형 만들기


262

enumTypeScript에서 다음 코드를 사용하여 만들 수 있습니다 .

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

그리고 값은 다음을 통해 액세스 할 수 있습니다.

e.hello;
e.world;

enum문자열 값 으로 with를 작성하는 방법

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

답변:


409

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

약간의 개선 :toString(): string { return this.value; }
psulek

@psulek 사실 타이프 라이터는 추론 할 것이다 toString그것을 반환 이후 수익률에게 문자열 this.valuevalueString 타입이다. 그래서 당신은 할 수없고 var x:number = E.hello.toString();만약 당신이한다면 var x = E.hello.toString();x도 타입 인 string것으로 추론됩니다 :)
basarat

2
@BASarat 이것은 타입 스크립트가 그러한 경우를 처리한다는 것이 사실이지만, 우리가 알 때마다 항상 리턴 타입으로 메소드를 장식했음을 의미합니다 .TS 컴파일러에는 필요하지 않지만 코더는 메소드 정의를 볼 때 알 수 있습니다. 반환하는 유형입니다.
psulek

@basarat get()메소드 를 대체하는 데 단점 이 return this.value있습니까? 그렇게하면 변환 할 때뿐만 아니라 액세스 할 때마다 문자열 값을 반환합니다 toString().
John

@basarat 만약 당신이 이와 같은 "enum"을 여러 개 가지고 있다면, 컴파일러는 구조적 타이핑 때문에 그것들을 구별하지 않을 것입니다-컴파일러는 value모든 타입의 멤버를 보고 그것들을 비슷한 타입으로 취급합니다. value그래도 회원을 비공개로 만들 수 있습니다. 이런 식으로 컴파일러는 그것을 보지 못하고 구조적 타이핑을 적용하려고 시도하지 않습니다.
Kirill G.

113

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

최신 TypeScript 2.4에는 다음과 같은 문자열 열거 형이 도입되었습니다.

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

    // Aliases
    RemoveUser = DeleteUser,
}

TypeScript 2.4에 대한 자세한 내용 은 MSDN 블로그를 참조하십시오 .


2
일반적 으로이 솔루션은 선호되지만 (실제 열거 형이므로) 열거 형 이름이 무엇인지 (따라서 '문자열') 매우 제한적입니다.
JasonS

2
현재 최고의 솔루션.
Alon Amir

2
이것에 새로운 것이 있습니까? 때문에 States[str]요즘 작동하지 않습니다. Type 'string' is not assignable to type 'States'
MrCroft

1
@MrCroft 다음 States[str as any]을 사용 하여 Typescript의 현재 (2.x) 버전에서 할 수 있습니다 .
psulek

States [str]는 내가 찾던 것입니다. 감사!
Martin Konicek

81

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.


1
선언 파일에서 비슷한 것을 어떻게 정의 할 수 있습니까?
Zev Spitz 2016

당신은 할 수 @ZevSpitz
데이비드 Sherret

현재 컴파일러를 사용하면 MyStringEnum에서 문자열 값을 잘못 입력하면 불평하지 않습니다. 문자열이 항상 유효한지 확인하기 위해 'Enforcer'인터페이스를 만들고 있습니다. 예를 들면 다음과 같습니다. interface MyStringEnumEnforcer {Member1 : MyStringEnum, Member2 : MyStringEnum} 그런 다음 const MyStringEnum : MyStringEnumEnforcer = {Member1 : "member1", Member2 : "member2"} 잘못된 유형의 문자열은 허용되지 않습니다. 원래 시나리오. 이 접근법에는 많은 의식이 있지만 안전을 좋아합니다.
jmorc


40

TypeScript 0.9.0.1에서는 컴파일러 오류가 발생하지만 컴파일러는 여전히 ts 파일을 js 파일로 컴파일 할 수 있습니다. 코드는 예상대로 작동하며 Visual Studio 2012는 자동 코드 완성을 지원할 수 있습니다.

업데이트 :

구문에서 TypeScript를 사용하면 문자열 값으로 열거 형을 만들 수 없지만 컴파일러를 해킹 할 수 있습니다.

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

운동장


1
멋진 해킹,하지만 당신은 스위치 문 예를 들어, 이러한 열거 / 상수를 사용할 수 없습니다 case Link.LEARN:얻을 것이다 Cannot convert 'Link.LEARN' to 'string'빌드 오류가 발생했습니다. 캐스팅이 작동하지 않습니다.
Gone Coding 코딩

@TrueBlueAussie 이것은 TSC 1.0.0.0을 실행하는 데 잘 작동하는 것 같습니다. 또한 어떤 이유로 든 case 상수에 문자열 상수 / 변수를 넣어야하는 경우 문자열로 캐스팅하면 작동합니다.
CodeAndCats

1
또한, 감사 @ zjc0816, 나는 :)이 솔루션 사랑을 괴물
CodeAndCats

그것이 내가 원했던 해결책입니다.
Murhaf Sousli

5
재미 있고, 왜 TypeScript가 이미 열거 형 문자열을 지원하지 않는지 궁금합니다. 많은 사람들이 이것을 원합니다 (포함).
Hendy Irawan

23

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('Bad');            // 🙁 

TypeScript 2.4 이상

버전 2.4에서 TypeScript는 문자열 열거 형을 기본적으로 지원하므로 위의 솔루션은 필요하지 않습니다. TS 문서에서 :

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE",
}

열거 형 키 이름이 문자열 값과 다른 경우 어떻게해야합니까 (예 : 매우 길기 때문에)?
CletusW

신경 쓰지 마! @ Łukasz-pniewski의 답변 아래
해결됨

인덱스 표현식이 'number'유형이 아니기 때문에 tslint는 Enum : Element를 역 맵핑 할 때 해당 String-Enum 예제에서 오류를 발생시킵니다. 나는 문제가 TS 문자열 열거 형에, 역 매핑 수의 문자열 열거 예제에서 주석 볼 수 없습니다 추측 typescriptlang.org/docs/handbook/release-notes/...을 - 이것은 TS 2.4 사실로 보인다 String-Enum이 도입되었지만 TS 2.6.2에서도 오류가 발생합니다. 예 : Colors["RED"]작동하지 않습니다. 이 문제를 해결하는 방법에 대한 아이디어 (JSON 변환에 필요).
masi

19

왜 열거 형의 문자열에 액세스하는 기본 방식을 사용하지 않습니까?

enum e {
  WHY,
  NOT,
  USE,
  NATIVE
}

e[e.WHY] // this returns string 'WHY'

2
이것은 내가 찾던 대답입니다, 감사합니다! 다른 솔루션은 영리한 해결 방법이지만 매우 간단합니다.)
M--

19
이것은 질문에 대답하지 않습니다. 문제는 열거 형의 문자열에 액세스하는 것에 관한 것이 아닙니다. enum Why { Because = "You Can't", Always = "Do Things That Way." };)
James Wilkins

0은 거짓, 디버그하기 어려운 숫자 값 열거 형을 사용할 때 문제가 있습니다
robmcm

@robmcm solved enum e {WHY = 1, NOT = 2, USE = 3, NATIVE = 4} e [e.WHY] // 문자열 'WHY'를 반환합니다.
Mjan-jan Stelling

16

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

1
이것은 나를 위해 일을 한 가장 간결한 방법이었습니다 ... 적어도 TS 1.8로 컴파일하기 위해 비계를 업데이트하는 방법을 알아낼 수있을 때까지
ThinkBonobo

그러나 이것의 한 가지 문제 <string>e.hello는 오류 를 유발한다는 것입니다. e.hello컴파일러는 여전히 숫자로 간주합니다. <number>e.hello그래도 작동합니다. 이 주위에 어떤 방법이 있습니까? 모든 I는 생각할 수 있습니다 <string><any>e.hello.
RainingChain

또 다른 문제는 열거 형 멤버가 열거 형 값과 같을 때입니다. 예 :enum Test { a = <any>"b", b = <any>"c", c = <any>"a" } Test.a === 'c'
RainingChain

이 방법을 항상 사용합니다. 문자열 열거 형의 바위. 컴파일러가 문자열 리터럴에 대한 첫 번째 클래스 지원은 없지만 두 번째 클래스 지원은 실망합니다. 컴파일러는 실제로 .d.ts 파일에서 <any> 해킹을 사용하지 못하도록 알기 때문에 실제로 알고 있습니다. 그것의 그러나 완전히 멈추지 않습니다.
CodeAndCats

Btw, 문자열 값을 문자열 열거 형 값과 비교하려면 <any>다음에 캐스팅하는 대신 다음과 같이 캐스팅하십시오 <string>.someStringValue == someEnumValue.toString()
CodeAndCats

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: // ...
}

1
좋은 답변입니다! 상속 지원을 통해 Enum과 같은 객체를 만드는 데 어려움을 겪고있었습니다.
DanielM

클래스 기반 Enum을 사용하는 예 : goo.gl/SwH4zb(TypeScript의 놀이터 링크).
DanielM

8

해킹 방법은 다음과 같습니다.-

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"

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 " 
}

4

방금 인터페이스를 선언하고 해당 유형의 변수를 사용하여 열거 형에 액세스합니다. TypeScript는 열거 형에서 무언가가 바뀌면 불평하기 때문에 인터페이스와 열거 형을 동기화 상태로 유지하는 것은 실제로 쉽습니다.

오류 TS2345 : 'typeof EAbFlagEnum'유형의 인수를 'IAbFlagEnum'유형의 매개 변수에 지정할 수 없습니다. 'typeof EAbFlagEnum'유형에 'Move'속성이 없습니다.

이 방법의 장점은 다양한 상황에서 열거 형 (인터페이스)을 사용하기 위해 유형 캐스팅이 필요하지 않으므로 스위치 / 케이스와 같은 더 많은 유형의 상황이 지원됩니다.

// 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
}

플래그는 저에게 또 다른 필수 요소 였으므로이 예제에 추가하고 테스트를 포함하는 NPM 모듈을 만들었습니다.

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


이것은 정의와 가져 오기를 혼합 할 수있는 유일한 대답입니다. 좋은! export default EAbFlagEnum as IAbFlagEnum;변수를 다시 선언하는 대신 사용할 수 있습니다 . 나는 또한 <any>열거 형 에서 캐스트를 제거 했는데 정상적으로 작동합니다.
기 illa F.

4

업데이트 : 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

이것이 바로 내가 필요한 것입니다! 대문자 / 소문자 차이로 표시된 것처럼 키 이름이 문자열 값과 다른 것을 지원합니다. 감사!
CletusW

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'

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

소스 링크에는 문자열 리터럴 유형을 달성하는 더 쉽고 쉬운 방법을 찾을 수 있습니다


2

많은 답변이 있지만 완전한 해결책이 없습니다. 허용 된 답변과의 문제 enum { this, one }는 많은 파일을 통해 사용되는 문자열 값을 분산 시킨다는 것입니다. "업데이트"도 마음에 들지 않습니다. 복잡하고 유형도 활용하지 않습니다. Michael Bromley의 대답 이 가장 정확 하다고 생각 하지만 인터페이스는 번거롭고 유형과 관련이 있습니다.

TypeScript 2.0을 사용하고 있습니다. * 다음은 수행 할 작업입니다.

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

let greet: Greeting = Greeting.hello

또한 유용한 IDE를 사용할 때 훨씬 좋은 유형 / 호버 오버 정보가 있습니다. 단점은 문자열을 두 번 작성해야하지만 적어도 두 곳에만 있다는 것입니다.


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...
}

1

최근 TypeScript 1.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)

0

이 방법으로 시도해야한다고 생각합니다.이 경우 변수의 값은 변경되지 않으며 열거 형과 같이 작동합니다. 클래스처럼 사용하는 유일한 단점은 실수로 정적 변수의 값을 변경할 수 있다는 것입니다. 우리는 열거 형을 원하지 않습니다.

namespace portal {

export namespace storageNames {

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

  }
}

0
export enum PaymentType {
                Cash = 1,
                Credit = 2
            }
var paymentType = PaymentType[PaymentType.Cash];

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


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

레거시 코드 / 데이터 스토리지를 지원하려는 경우 숫자 키를 유지할 수 있습니다.

이렇게하면 값을 두 번 입력하지 않아도됩니다.


0

문자열이있는 매우 간단한 Enum (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))
}

0

나는 아래와 같이 TypeScript 1.5에서 시도했고 그것은 나를 위해 일했다.

module App.Constants {
   export enum e{
        Hello= ("Hello") as any,
World= ("World") as any
    }
}

0

나는 typescript enum (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);
    }

-1

TypeScript 0.9.0.1

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

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

TypeScript 놀이터


결과 JavaScript는 작동하지만 컴파일러 오류가 발생합니다 Cannot convert 'string' to 'e'..
Sam
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.