As I was translating a large JavaScript project into TypeScript, something caught my attention. Consider a module that looks like this:
WinConstants.ts
export = {
"no_win":0,
"win":1,
"big_win":2,
"mega_win":3
}
I wanted to make it truly constant, so I refined it as follows:
WinConstants.ts
class WinConstants{
readonly no_win:0;
readonly win:1;
readonly big_win:2;
readonly mega_win:3;
}
export = new WinConstants();
Pretty neat, right? With that out of the way, onto the next module... Or maybe not. I forgot to replace ":"
with "="
, and TypeScript did not alert me about this. As a result, all values are now undefined
. This mistake might slip through until runtime, bringing back some uncertainty reminiscent of JavaScript! The whole purpose of transitioning to TypeScript, where errors are caught by the compiler, seems to have been compromised in this case. If literal types weren't in play, this issue wouldn't have occurred, since literal numbers would not be considered as types.
So what can we do now? Don't get me wrong, I appreciate the benefits of literal types, but the current syntax is working against me. These oversights may not only happen during translation, but also when writing code and accidentally using a :
instead of an =
in JSON style format.
Any suggestions?