Typescript 中的 Java 枚举等效项

Den*_*nov 2 java enums typescript typeorm nestjs

你能告诉我是否可以在 Typescript 中创建这样的枚举吗?

public enum FooEnum {

    ITEM_A(1), ITEM_B(2), ITEM_C(3);

    private int order;

    private FooEnum (int order) {
        this.order = order;
    }

    public int getOrder() {
        return order;
    }
}
Run Code Online (Sandbox Code Playgroud)

我有这样的枚举:

export enum FooEnum {
  ITEM_A = 'ITEM_A',
  ITEM_B = 'ITEM_B',
  ITEM_C = 'ITEM_C',
}
Run Code Online (Sandbox Code Playgroud)

我在 TypeORM 实体中使用

@Column({ type: 'enum', enum: FooEnum })
foo!: FooEnum
Run Code Online (Sandbox Code Playgroud)

我需要将枚举值分配给数字来定义它们的优先级。可以这样做吗?

我还想用常量创建值对象,如下所示,但我不知道在实体上使用此类,仍像“ITEM_A”字符串一样保存 Foo.ITEM_A

class Foo {
  public static ITEM_A = new Country(1);
  public static ITEM_B = new Country(2);
  public static ITEM_C = new Country(3);

  constructor(order: number) {
    this.order = order;
  }

  readonly order: number;
}
Run Code Online (Sandbox Code Playgroud)

Mr.*_*irl 7

本文介绍了一种static readonly使用 TypeScript 封装实例变量的方法。

“在 Typescript 中重新创建高级枚举类型”

这是完整的要点(带评论):

GitHub Gist / NitzanHen / ts-enums-complete.ts

这是一个Country“枚举”类的示例:

class Country {
  static readonly FRANCE = new Country('FRANCE', 1);
  static readonly GERMANY = new Country('GERMANY', 2);
  static readonly ITALY = new Country('ITALY', 3);
  static readonly SPAIN = new Country('SPAIN', 4);

  static get values(): Country[] {
    return [
      this.FRANCE,
      this.GERMANY,
      this.ITALY,
      this.SPAIN
    ];
  }

  static fromString(name: string): Country {
    const value = (this as any)[name];
    if (value) return value;
    const cls: string = (this as any).prototype.constructor.name;
    throw new RangeError(`Illegal argument: ${name} is not a member of ${cls}`);
  }

  private constructor(
    public readonly name: string,
    public readonly order: number
  ) { }

  public toJSON() {
    return this.name;
  }
}

export default Country;
Run Code Online (Sandbox Code Playgroud)

用法

const selectedCountry: Country = Country.FRANCE;

console.log(selectedCountry.order);
Run Code Online (Sandbox Code Playgroud)