Typescript相当于Java的枚举(或C#的结构)

时间:2017-02-27 08:14:33

标签: typescript enums

我需要在Typescript中创建一个枚举。但是,您只能使用与C#类似的基于整数的枚举。仍然C#有结构来做非整数相关的事情。这似乎没有在TypeScript中实现。我需要“解决”还是有实施的东西?

我尝试实现的是TypeScript与此Java代码的等价物:

public enum Something { 

 PENNY("PENNY"), NICKLE("NICKLE"); 

 private String value; 

 private Something (String value) { 
  this.value = value; 
 } 

};

4 个答案:

答案 0 :(得分:2)

虽然您无法提供显式字符串值(仅限数字),但可以通过索引及其名称引用TypeScript枚举。您可以通过将数字传递回枚举来访问其名称,如下所示:

enum Direction { Up, Down, Left, Right }

console.info(Direction[Direction.Up]); // "Up"

或者,使用地图:

const directionText = new Map([
  [Direction.Up, 'UP'],
  // ...
]);

答案 1 :(得分:1)

您可以像这样简单地创建枚举。它的工作方式与Java或C#相同。

export enum ControlType {
  INPUT,
  SELECT,
  DATEPICKER
}


console.log(ControlType.INPUT); // returns 0
console.log(ControlType[ControlType.INPUT]); // returns INPUT

您也可以添加其他信息,但正如您所注意到的,只能使用类型编号。

export enum ControlType {
  INPUT = 3,
  SELECT = 6,
  DATEPICKER = "abc".length // computed member
}

console.log(ControlType.INPUT); // returns 3

如果您想添加其他不属于类型编号但有解决方法的成员,事情会变得更加困难。您必须将类型设置为<any>

export enum ControlType {
  INPUT = <any>'input',
  SELECT = <any>'select',
  DATEPICKER = <any>'date-picker'
}

console.log(ControlType.INPUT); // returns 'input'

这里的缺点是您只能将这些值与any类型的其他变量匹配。例如在;的情况下;

(ControlType.INPUT === myVar) {..}

myVar必须声明为myVar: any = 'input';,即使它是一个字符串。

答案 2 :(得分:1)

在查看这个问题时,我发现自打字稿2.4以来,他们已经拥有了String Enums支持。它类似于java的枚举,非常直观易用。

From the release notes for TypeScript 2.4:

  

String Enums

     

TypeScript 2.4现在允许枚举成员包含字符串初始值设定项。

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

需要注意的是,无法对字符串初始化的枚举进行反向映射以获取原始枚举成员名称。换句话说,你不能写颜色[&#34; RED&#34;]来获得字符串&#34; Red&#34;。

答案 3 :(得分:1)

现在是typescript@3.5.2,但是像Java或C#这样的枚举-不存在。 所以我写了一些解决方法。

/**
 * Decorator for Enum.
 * @param {string} idPropertyName - property name to find enum value by property value. Usage in valueOf method
 * @return constructor of enum type
 */
export function Enum<T = any>(idPropertyName?: keyof T) {
    // tslint:disable-next-line
    return function <T extends (Function & EnumClass)>(target: T): T {
        const store: EnumStore = {
            name: target.prototype.constructor.name,
            enumMap: {},
            enumMapByName: {},
            enumValues: [],
            idPropertyName: idPropertyName
        };
        // Lookup static fields
        for (const fieldName of Object.keys(target)) {
            const value: any = (target as any)[fieldName];
            // Check static field: to be instance of enum type
            if (value instanceof target) {
                const enumItem: Enumerable = value;
                let id = fieldName;
                if (idPropertyName) {
                    id = (value as any)[idPropertyName];
                    if (typeof id !== "string" && typeof id !== "number") {
                        const enumName = store.name;
                        throw new Error(`The value of the ${idPropertyName} property in the enumeration element ${enumName}.${fieldName} is not a string or a number: ${id}`);
                    }
                }
                if (store.enumMap[id]) {
                    const enumName = store.name;
                    throw new Error(`An element with the identifier ${id}: ${enumName}.${store.enumMap[id].enumName} already exists in the enumeration ${enumName}`);
                }
                store.enumMap[id] = enumItem;
                store.enumMapByName[fieldName] = enumItem;
                store.enumValues.push(enumItem);
                enumItem.__enumName__ = fieldName;
                Object.freeze(enumItem);
            }
        }
        target.__store__ = store;
        Object.freeze(target.__store__);
        Object.freeze(target);
        return target;
    };
}

/** Key->Value type */
export type EnumMap = {[key: string]: Enumerable};

/** Type for Meta-Data of Enum */
export type EnumClass = {
    __store__: EnumStore
};

/** Store Type. Keep meta data for enum */
export type EnumStore = {
    name: string,
    enumMap: EnumMap,
    enumMapByName: EnumMap,
    enumValues: Enumerable[],
    idPropertyName?: any
};

/** Enum Item Type */
export type EnumItemType = {
    __enumName__: string;
};

/** Interface for IDE: autocomplete syntax and keywords */
export interface IStaticEnum<T> extends EnumClass {

    new(): {enumName: string};

    values(): ReadonlyArray<T>;

    valueOf(id: string | number): T;

    valueByName(name: string): T;
}

/** Base class for enum type */
export class Enumerable implements EnumItemType {
    // tslint:disable:variable-name
    // stub. need for type safety
    static readonly __store__ = {} as EnumStore;
    // Initialize inside @Enum decorator
    __enumName__ = "";
    // tslint:enable:variable-name

    constructor() {
    }

    /**
     * Get all elements of enum
     * @return {ReadonlyArray<T>} all elements of enum
     */
    static values(): ReadonlyArray<any> {
        return this.__store__.enumValues;
    }

    /**
     * Lookup enum item by id
     * @param {string | number} id - value for lookup
     * @return enum item by id
     */
    static valueOf(id: string | number): any {
        const value = this.__store__.enumMap[id];
        if (!value) {
            throw new Error(`The element with ${id} identifier does not exist in the $ {clazz.name} enumeration`);
        }
        return value;
    }

    /**
     * Lookup enum item by enum name
     * @param {string} name - enum name
     * @return item by enum name
     */
    static valueByName(name: string): any {
        const value = this.__store__.enumMapByName[name];
        if (!value) {
            throw new Error(`The element with ${name} name does not exist in the ${this.__store__.name} enumeration`);
        }
        return value;
    }

    /** Get enum name */
    get enumName(): string {
        return this.__enumName__;
    }

    /** Get enum id value or enum name */
    toString(): string {
        const clazz = this.topClass;
        if (clazz.__store__.idPropertyName) {
            const self = this as any;
            return self[clazz.__store__.idPropertyName];
        }
        return this.enumName;
    }

    private get topClass(): EnumClass {
        return this.constructor as any;
    }
}

/** 'Casting' method to make correct Enum Type */
export function EnumType<T>(): IStaticEnum<T> {
    return (<IStaticEnum<T>> Enumerable);
}

现在,它很容易使用

// node-module
// import {Enum, EnumType} from "ts-jenum";

@Enum("value")
class Something extends EnumType<Something>() {

    static readonly PENNY = new Something("Penny");
    static readonly NICKLE = new Something("Nickle");

    constructor(readonly value: string) {
        super();
    }
}

// Usage example
console.log("" + Something.PENNY);              // Penny
console.log("" + Something.NICKLE);             // Nickle
console.log(Something.values());                // [Something.PENNY, Something.NICKLE]
console.log(Something.valueByName("PENNY"));    // Something.PENNY
console.log(Something.PENNY.enumName);          // PENNY

以上所有都是安全类型。