How to write a constant in the TypeScript?
source link: https://medium.com/@przemyslaw.jan.beigert/how-to-write-a-constant-in-the-typescript-64d296c1e003
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Introduction
TypeScript was designed as a superset of JavaScript, so TS types should not affect JS’s runtime. However there’s couple ways to define constant value.
Object as const:
as const
will be removed in the compilation time, so only an object will exists in the run time. Adding as const
will change type definition from:
into:
Looks pretty simple however it wouldn’t be so easy to create a type definition of BUTTON_SIZES
value.
Enum:
Looks similar to the previous case however this code will be complied into:
It’s the same object as in previous case but it takes more space in the final bundle.
Big advantage is the fact that you don’t have to create a separate type for a ButtonSizeValue
because enum BUTTON_SIZE
can be use as a type of a value.
But what about case when enum has numbers instead of strings:
Will be complied to:
And this code it the same that:
So value become a key and key becomes a value…
Const enum:
Almost the same code as in the previous example will be removed in compilation time.
Usage of enum like this:
Will be complied into:
Looks much better than previous example however there’s couple od disadvantages:
Because there’s no object in the run time you can not use const enum as an object. In that case removing const
from enum definition is gonna resolve the problem.
Union:
The simplest way will be:
Type definition will be removed in compilation time and complier will prevent us to pass unknown or different strings.
Is fast in the implementation but has the same disadvantages as const enum. Also changing value (e.g. “medium” into “regular”) requires modification of each usage, not just one like in enum/const enum.
Summary:
Is hard to choose the best way, all of them have advantages and disadvantages. In my opinion const enum can be good first choice.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK