typescript中的java enum等价物

ufj5ltwl  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(378)

你能告诉我是否有可能在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;
    }
}

我有这样的枚举:

export enum FooEnum {
  ITEM_A = 'ITEM_A',
  ITEM_B = 'ITEM_B',
  ITEM_C = 'ITEM_C',
}

我在typeorm实体中使用的

@Column({ type: 'enum', enum: FooEnum })
foo!: FooEnum

我需要给数字分配枚举值来定义它们的优先级。有可能吗?
我还想用常量创建value对象,如下面所示,但我不知道如何在entity上使用这个类来保存foo.item\u,比如'item\u 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;
}
0s7z1bwu

0s7z1bwu1#

本文描述了一种封装
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;

用法

const selectedCountry: Country = Country.FRANCE;

console.log(selectedCountry.order);

相关问题