shal
shal

Reputation: 3044

What to do with a danger of literal types?

I translate a big JS project to TS project and noticed something. For example I have a module, which looks like this:

WinConstants.ts

export = {
  "no_win":0,
  "win":1,
  "big_win":2,
  "mega_win":3
}

I want to make it really constant, so I restrict it like this:

WinConstants.ts

class WinConstants{
  readonly no_win:0;
  readonly win:1;
  readonly big_win:2;
  readonly mega_win:3;
}

export = new WinConstants();

Pretty cool huh? Done with it, now go translate next module. Right? Not so fast. I forgot to replace ":"s with "="s and TypeScript does not warn me about it. All values are now undefined. It may go under the radar until I see it in runtime... Welcome back to JS uncertainty! The whole point of translating things to TS, when you rely on compiler's errors, just cancelled itself... If there had been no literal types, this would have never happened, because literal numbers in this case wouldn't have been types.

So what to do? Don't get me wrong, I love literal types, they help a lot, but the syntax is now against me. These kind of things may go unnoticed not only when I translate, but when I write something and accidentally put : in JSON style rather than = sign.

Any ideas?

Upvotes: 0

Views: 36

Answers (1)

Finn Poppinga
Finn Poppinga

Reputation: 279

Neither your first, nor your second approach are good, as you are exporting a constant object or an instance of a class.

You should use an enum for this (more info).

export enum WinConstants {
  NO_WIN = 0,
  WIN = 1,
  BIG_WIN = 2,
  MEGA_WIN = 3
}

Upvotes: 1

Related Questions