Search code examples
typescriptclass-constants

How to implement class constants?


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 wonder if 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


Solution

  • 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.