Declare a constant in a Typescript Class

前端 未结 1 1716
傲寒
傲寒 2021-01-19 12:24

What is is the best way to declare a constant in a TypeScript class?

相关标签:
1条回答
  • 2021-01-19 13:10

    You can't declare a constant, you can declare a readonly field, which is weaker then what you would expect from a constant but might be good enough:

    class MyClass {
        static readonly staticReadOnly = 10;
        readonly instanceReadonly = 10;
    }
    
    console.log(MyClass.staticReadOnly);
    console.log((new MyClass).instanceReadonly);
    

    I say it's weaker because at runtime the value can be changed, and more over even within the type system we can violate readonly without a type assertion:

    let mutable: { instanceReadonly: number } = new MyClass() // valid assignment
    mutable.instanceReadonly = 11; // we just changed a readonly field
    

    If you can I would stick with a regular const declaration outside the class.

    0 讨论(0)
提交回复
热议问题