tbsklg
tbsklg

Reputation: 3

How to implement TypeScript enums?

I have implemented a TypeScript enum in the following way:

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

I would like to know if this is a good practice to implement enums in TypeScript beside using numeric and string-based enums described in https://www.typescriptlang.org/docs/handbook/enums.html.

Upvotes: 0

Views: 409

Answers (1)

meriton
meriton

Reputation: 70564

Representing enum values as objects has the disadvantage that you need custom serialization / deserialization code to convert to and from JSON, which is rather cumbersome.

That's why, in idiomatic typescript, enum "properties" are typically stored separately from enum values, for instance like this:

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; 

which allows you to use the Size type in interfaces to describe the shape of your JSON objects:

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

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

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

Note that it is not strictly necessary to declare a class for SizeInfo - if you prefer, you can use an interface instead.

Upvotes: 1

Related Questions