2017-07-17 1 views
0

Ich bin seit langer Zeit Java-Programmierer und jetzt studiere ich Angular, was mich dazu brachte, TypeScript zu studieren.Ist es möglich, Enums in TypeScript zu implementieren, die Parameter wie in Java erhalten?

Ich entwickle etwas einfach zu üben und ich stieß auf eine Situation, wo ich in der Java-Welt ein Enum erstellen würde.

Von dem, was ich sah, unterstützt TypeScript dieses Enum-Konzept, im Vergleich zu Java ist es jedoch ziemlich begrenzt.

Um die Einschränkungen von Enum in TypeScript zu umgehen, dachte ich über eine Klasse, die sich wie ein Enum verhält.

Ist die Implementierung laut Good Practices in der TypeScript-Welt "okay"?

Ist es möglich, Enums in TypeScript zu implementieren, die Parameter wie in Java erhalten? Oder ist das wirklich nur durch Klassen möglich?

export class MyEnum { 

    public static readonly ENUM_VALUE1 = new MyEnum('val1_prop1', 'val1_prop2'); 
    public static readonly ENUM_VALUE2 = new MyEnum('val2_prop1', 'val2_prop2'); 
    public static readonly ENUM_VALUE3 = new MyEnum('val3_prop1', 'val3_prop2'); 

    private readonly _prop1: string; 
    private readonly _prop2: string; 

    private constructor(prop1: string, prop2: string){ 
     this._prop1 = prop1; 
     this._prop2 = prop2; 
    } 

    get prop1(): string{ 
     return this._prop1; 
    } 

    get prop2(): string{ 
     return this._prop2; 
    } 
} 

Antwort

0

Sie könnten einen Enum-Typ mit einer any Besetzung wie unten erzwingen. Aber ich denke, die Klassenlösung ist besser.

class MyEnumType { 
    constructor(public val1: number, public val2: number) { } 
} 

enum MyEnum { 
    Enum1 = <any>new MyEnumType(1, 2), 
    Enum2 = <any>new MyEnumType(3, 4) 
} 

let enum1 = MyEnum.Enum1; 
console.log(enum1 == MyEnum.Enum1); // true 
console.log((<MyEnumType><any>enum1).val1); // 1 
Verwandte Themen