如何实现TypeScript枚举?

时间:2018-10-08 13:03:09

标签: typescript

我已经通过以下方式实现了TypeScript枚举:

export class Size{
    static SMALL = new Size('smaller than 100', 1, 100);
    static MEDIUM = new Size('smaller than 1000', 1, 1000);

    readonly description: string;
    readonly from: number;
    readonly to: number;

    private constructor(description: string, from: number, to: number){
        this.description = description;
        this.from = from;
        this.to = to;
    }
}

除了使用https://www.typescriptlang.org/docs/handbook/enums.html中所述的基于数字和基于字符串的枚举之外,我想知道这是否是在TypeScript中实现枚举的好习惯。

1 个答案:

答案 0 :(得分:0)

将枚举值表示为对象有一个缺点,那就是您需要自定义序列化/反序列化代码才能与JSON相互转换,这非常麻烦。

这就是为什么在惯用打字稿中,枚举“属性”通常与枚举值分开存储的原因,例如:

export class SizeInfo {
    constructor(
        public readonly from: number,
        public readonly to: number,
        public readonly description: string
    ) { }
}

export const SizeInfos = {
  small: new SizeInfo(1, 100, "smaller than 100"),
  medium: new SizeInfo(101, 1000, "smaller than 1000"),
}

export type Size = keyof typeof SizeInfos; 

它允许您在接口中使用Size类型来描述JSON对象的形状:

export interface Order {
    item: string;
    size: Size;
}    

const order: Order = JSON.parse(`{
    item: "adsf",
    size: "small",
}`);

const descr = SizeInfos[order.size].description;

请注意,不必严格为SizeInfo声明类-如果愿意,可以改用接口。