We don't have to use Enums on TypeScript? 【Discussion】

taishi

Taishi

Posted on May 3, 2022

We don't have to use Enums on TypeScript? 【Discussion】

Hi, Devs! I am Taishi, a software developer in Vancouver!

I have been thinking about using Enums lately, and my conclusion is that we should NOT use Enums if possible.

But why?

Enums has impact on compiled JavaScript files

Usually tsc command removes all the TypeScript unique stuff such as

  • Type definition
  • Interface definition
  • Type annotation

This means TypeScript doesn't have any effect on the compiled JavaScript files.

On the other hand, TypeScript has some impact on JS files if you use Enums.

Let's compare them!

Case 1: Union types

TypeScript

type BigTechz = "Google" | "Apple" | "Amazon";

const myFav: BigTechz = "Apple";
Enter fullscreen mode Exit fullscreen mode

Javascript after tsc

"use strict";
const myFav = "Apple";
Enter fullscreen mode Exit fullscreen mode

Case 2: Enums

enum BigTechz {
  Google = "Google",
  Apple = "Apple",
  Amazon = "Amazon",
}

const myFav: BigTechz = BigTechz.Apple;
Enter fullscreen mode Exit fullscreen mode

Javascript after tsc

"use strict";
var BigTechz;
(function (BigTechz) {
  BigTechz["Google"] = "Google";
  BigTechz["Apple"] = "Apple";
  BigTechz["Amazon"] = "Amazon";
})(BigTechz || (BigTechz = {}));
const myFav = BigTechz.Apple;
Enter fullscreen mode Exit fullscreen mode

My thought

As you can see above, Enums stays on a JavaScript file as an object...which causes a bigger bundle size.
And more importantly, I think TypeScript shouldn't have any impact on compiled JavaScript files.

TypeScript is basically a type checker when you write codes and when you compile TS files with tsc command.

Most of the times you can use other TS syntax instead of Enums, and I think we should do that if possible (Maybe I just prefer Union types🙄)!

I'd like to hear other devs' opinion about this topic, and I appreciated if you leave a comment!

Thanks!

💖 💪 🙅 🚩
taishi
Taishi

Posted on May 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related