Declare a constant in a Typescript Class

2020-04-10 02:38发布

问题:

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

回答1:

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.