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 \'co
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);
}
}
All of the replies with readonly
are only suitable when this is a pure TS environment - if it's ever being made into a library then this doesn't actually prevent anything, it just provides warnings for the TS compiler itself.
Static is also not correct - that's adding a method to the Class, not to an instance of the class - so you need to address it directly.
There are several ways to manage this, but the pure TS way is to use a getter
- exactly as you have done already.
The alternative way is to put it in as readonly
, but then use Object.defineProperty
to lock it - this is almost the same thing that is being done via the getter, but you can lock it to have a value, rather than a method to use to get it -
class MyClass {
MY_CONSTANT = 10;
constructor() {
Object.defineProperty(this, "MY_CONSTANT", {value: this.MY_CONSTANT});
}
}
The defaults make it read-only, but check out the docs for more details.