BeetleJuice BeetleJuice - 1 month ago 21
TypeScript Question

How to implement class constants in typescript?

In TypeScript, the

const
keyword cannot be used to declare class properties. Doing so causes the compiler to 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

Answer

TypeScript 2.0 has the readonly modifier:

class MyClass {
    readonly myReadonlyProperty = 1;
}

new MyClass().myReadonlyProperty = 5; // error

It's not exactly a constant because it allows assignment in the constructor, but this is the simplest option.

Comments