Declare a constant in a Typescript Class

2020-04-10 02:40发布

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

1条回答
神经病院院长
2楼-- · 2020-04-10 03:19

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.

查看更多
登录 后发表回答