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.