【问题标题】:Java enum equivalent in TypescriptTypescript 中的 Java 枚举等价物
【发布时间】:2021-03-22 03:39:29
【问题描述】:

你能知道是否可以在 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

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

我也有想法创建带有常量的值对象,如下所示,但我不知道在实体上使用此类,仍将 Foo.ITEM_A 保存为 '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;
}

【问题讨论】:

  • Java 和这个有什么关系?
  • @RobertHarvey 因为问题涉及将 Java 代码移植到 TypeScript。并非所有 Web 开发人员都是 Java 开发人员。
  • 您可以创建一个具有只读属性的类并将其实例设为只读。见:Recreating advanced Enum types in Typescript

标签: java typescript enums nestjs typeorm


【解决方案1】:

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

"Recreating advanced Enum types in Typescript"

这是完整的要点(带有 cmets):

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

这是一个示例Country“enum”类:

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

【讨论】:

  • 谢谢,它看起来正是我想要的:) 我去试试
  • 我试过了,值是从 DB 映射的,但是 NestJS 将它序列化为 json 响应中的对象。我也实现了 toJSON 方法
  • @DenisStephanov toJSON 方法不是标准方法...只是 name 值的示例 getter。我会查找 NestJS 如何序列化一个类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-15
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多