在Typescript类中声明一个常量 [英] Declare a constant in a Typescript Class

查看:38
本文介绍了在Typescript类中声明一个常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TypeScript 中声明常量的最佳方法是什么?

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

推荐答案

您不能声明常量,可以声明 readonly 字段,它比您从常数中所期望的要弱,但可能足够好:

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

如果可以的话,我会坚持使用常规的 const 类外的声明。

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

这篇关于在Typescript类中声明一个常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆