DEV Community

Wes
Wes

Posted on • Originally published at goulet.dev on

Don't use TypeScript enum

Trying my hand at a zero-nuance take.

Don't do this

enum Shape {
  Sphere,
  Rectangle,
  Triangle,
}

const ball = {
  shape: Shape.Sphere,
};
Enter fullscreen mode Exit fullscreen mode

Do this instead

type Shape = "Sphere" | "Rectangle" | "Triangle";

const ball = {
  shape: "Sphere",
};
Enter fullscreen mode Exit fullscreen mode

Why?

Seems I'm not good at "zero-nuance", I feel compelled to explain the why behind this take... at least I'll keep it brief.

Enums are not part of the JavaScript language, so the TypeScript compiler generates different runtime code when you use enums. You aren't writing "JavaScript with types" any more. You are writing a different language that transpiles to JS. Don't do that. Keep it simple.

TypeScript is great for type checking as a dev-time benefit: it's additive, you can strip off the types and you still have JavaScript. You can even add types to JavaScript files with JSDoc comments - no need for a build step to strip off types, ship/debug the code you write, even better!

Related Posts

Top comments (0)