DEV Community

loading...

Discussion on: Using Typescript string enums? Consider string literals!

Collapse
juliang profile image
Julian Garamendy • Edited

I would add that a benefit of string literal types is that they don't emit anything.

As opposed to a simple enum like this:

enum BannerType {
    Warning,
    Danger
}

resulting in this:

var BannerType;
(function (BannerType) {
    BannerType[BannerType["Warning"] = 0] = "Warning";
    BannerType[BannerType["Danger"] = 1] = "Danger";
})(BannerType || (BannerType = {}));

I like TypeScript when it's just type annotations, so I don't need to guess what's happening at runtime.

Here's an example in the TS Playground

Collapse
michaeljota profile image
Michael De Abreu

You can use const enum if you don't like that behavior.

Collapse
juliang profile image
Julian Garamendy • Edited

Yes, but I don't think they work when using the --isolatedModules compiler option.

I mean they work but only within a module. You can't export a const enum.

Thread Thread
michaeljota profile image
Michael De Abreu

If you have types imports and exports, most of the type checking won't work when you use isolated modules.

Collapse
thomvaill profile image
Thomas Vaillant

Unfortunately const enums are not supported anymore by babel :(
github.com/babel/babel/issues/8741

Forem Open with the Forem app