Enums with explicit values

suggest change

By default all enum values are resolved to numbers. Let’s say if you have something like

enum MimeType {
  JPEG,
  PNG,
  PDF
}

the real value behind e.g. MimeType.PDF will be 2.

But some of the time it is important to have the enum resolve to a different type. E.g. you receive the value from backend / frontend / another system which is definitely a string. This could be a pain, but luckily there is this method:

enum MimeType {
  JPEG = <any>'image/jpeg',
  PNG = <any>'image/png',
  PDF = <any>'application/pdf'
}

This resolves the MimeType.PDF to application/pdf.

Since TypeScript 2.4 it’s possible to declare string enums:

enum MimeType {
  JPEG = 'image/jpeg',
  PNG = 'image/png',
  PDF = 'application/pdf',
}

You can explicitly provide numeric values using the same method

enum MyType {
   Value = 3,
   ValueEx = 30,
   ValueEx2 = 300
}

Fancier types also work, since non-const enums are real objects at runtime, for example

enum FancyType {
   OneArr = <any>[1],
   TwoArr = <any>[2, 2],
   ThreeArr = <any>[3, 3, 3]
}

becomes

var FancyType;
(function (FancyType) {
    FancyType[FancyType["OneArr"] = [1]] = "OneArr";
    FancyType[FancyType["TwoArr"] = [2, 2]] = "TwoArr";
    FancyType[FancyType["ThreeArr"] = [3, 3, 3]] = "ThreeArr";
})(FancyType || (FancyType = {}));

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents