是否可以在 TypeScript 中实现像 Java 中一样接收参数的枚举?



我做Java程序员很长时间了,现在我正在学习Angular,这促使我学习TypeScript。

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

从我所看到的,TypeScript支持这个枚举概念,但是,与Java相比,它是相当有限的。

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

根据 TypeScript 世界中的良好实践,下面的实现是否"正常"?

是否可以在 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 中实现像 Java 中那样接收参数的枚举?或者这真的只能通过课堂来实现吗?

我不这么认为。
不过,有一些库可以做这种事情:https://lmfinney.wordpress.com/2017/07/12/ts-enums-bringing-java-style-enums-to-typescript/

但它实际上只是您正在做的事情的更全面的功能版本。

您可以使用如下所示的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

相关内容

最新更新