Want to implement class constants in typescript? TypeScript 2.0 has the readonly modifier:
1 2 3 4 5 6 7 8 9 10 | class MyClass { readonly myReadOnlyProperty = 1; myMethod() { console.log(this.myReadOnlyProperty); this.myReadOnlyProperty = 5; // error, readonly } } new MyClass().myReadOnlyProperty = 5; // error, readonly |
It’s not exactly a constant because it allows assignment in the constructor, but that’s most likely not a big deal.
An alternative is to use the static keyword with readonly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class MyClass { static readonly myReadOnlyProperty = 1; constructor() { MyClass.myReadOnlyProperty = 5; // error, readonly } myMethod() { console.log(MyClass.myReadOnlyProperty); MyClass.myReadOnlyProperty = 5; // error, readonly } } MyClass.myReadOnlyProperty = 5; // error, readonly |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.