Member-only story
A Good Practice? Expressing A Set of Values with String Literals in TypeScript
Different language has different way to best express oneself onto it, I guess this is what is called as Idiom. It struck me that I start to think that expressing a set of values in TypeScript with literal strings is the better method…. Expressing the value as literal STRINGs !!!! Literal STRINGssss !!!
In other languages, it is a good practice to provide enumeration in order to express possible values in a set (e.g. in Java) This is due to enum’s values can be leveraged by the IDE, and the compiler to test whether the code are abiding in the correct typing. This hugely eliminates small typos to cause havoc in your system.
Now let us explore it with the context of TypeScript. Below is the TypeScript way to express similar enumeration construct.
type ScrollableEvents = "top" | "bottom"
TypeScript does not allow the types to be written with variables or constants (const
is just a syntactic sugar which works during and before it is transcompiled into Javascripts.)
So we stuck with literal string now… Is not this bad ?
It is not ! The type above will makes the whole IDE understood what it means to be a ScrollableEvents, and what values are allowed. So it does protects you from giving invalid…