In TypeScript, the const
keyword cannot be used to declare class properties. Doing so causes the compiler to an error with "A class member cannot have the 'const' keyword."
I find myself in need to clearly indicate in code that a property should not be changed. I want the IDE or compiler to error if I attempt to assign a new value to the property once it has been declared. How do you guys achieve this?
I'm currently using a read-only property, but I'm new to Typescript (and JavaScript) and wonder whether there is a better way:
get MY_CONSTANT():number {return 10};
I'm using typescript 1.8. Suggestions?
PS: I'm now using typescript 2.0.3, so I've accepted David's answer
A class constant is declared inside a class with the const keyword. Class constants are case-sensitive. However, it is recommended to name the constants in all uppercase letters.
Use the readonly modifier to declare constants in a class. When a class field is prefixed with the readonly modifier, you can only assign a value to the property inside of the classes' constructor. Assignment to the property outside of the constructor causes an error.
Static − Once you declare a variable static they will be loaded in to the memory at the compile time i.e. only one copy of them is available. Final − once you declare a variable final you cannot modify its value again. Therefore, you can create a constant in Java by declaring the instance variable static and final.
To make any variable a constant, we must use 'static' and 'final' modifiers in the following manner: Syntax to assign a constant value in java: static final datatype identifier_name = constant; The static modifier causes the variable to be available without an instance of it's defining class being loaded.
TypeScript 2.0 has the readonly
modifier:
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.
Alternative Solution
An alternative is to use the static
keyword with readonly
:
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
This has the benefit of not being assignable in the constructor and only existing in one place.
Constants can be declare outside of classes and use within your class. Otherwise the get
property is a nice workaround
const MY_CONSTANT: string = "wazzup"; export class MyClass { public myFunction() { alert(MY_CONSTANT); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With