How to implement class constants?

后端 未结 8 1853
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  Happy的楠姐
    2020-12-22 18:43

    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.

提交回复
热议问题