How to implement class constants?

后端 未结 8 1862
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 17:40

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

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-22 18:29

    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.

提交回复
热议问题