【问题标题】:Is it possible to implement Enums in TypeScript that receive parameters like in Java?是否可以在 TypeScript 中实现像 Java 一样接收参数的枚举?
【发布时间】:2017-07-17 00:13:50
【问题描述】:

我是 Java 程序员很长一段时间,现在我正在学习 Angular,这导致我学习 TypeScript。

我正在开发一些易于实践的东西,我遇到了一种情况,在 Java 世界中我会创建一个 Enum。

据我所知,TypeScript 支持这个 Enum 概念,但是,与 Java 相比,它是相当有限的。

为了解决 TypeScript 中 Enum 的限制,我想使用一个行为类似于枚举的类。

根据 TypeScript 世界的良好实践,下面的实现是否“可以”?​​p>

是否可以在 TypeScript 中实现像 Java 一样接收参数的枚举?或者这真的只能通过课程实现吗?

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

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    是否可以在 TypeScript 中实现像 Java 一样接收参数的枚举?或者这真的只能通过课程实现吗?

    我不相信。
    不过,有一些图书馆可以处理这种事情:https://lmfinney.wordpress.com/2017/07/12/ts-enums-bringing-java-style-enums-to-typescript/

    但这实际上只是您所做工作的功能更全面的版本。

    【讨论】:

      【解决方案2】:

      您可以强制使用any 强制枚举类型,如下所示。但我认为类解决方案更好。

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-07
        • 2014-04-24
        • 1970-01-01
        • 2011-02-08
        • 2018-03-31
        • 1970-01-01
        • 2014-03-31
        • 2015-06-16
        相关资源
        最近更新 更多