为什么我们不能在 TypeScript 类中定义一个 const 字段,为什么静态只读不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46784333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't we define a const field in TypeScript class, and why static readonly is not working?
提问by Aditya
I want to use const
keyword in my program.
我想const
在我的程序中使用关键字。
export class Constant {
let result : string;
private const CONSTANT = 'constant'; //Error: A class member cannot have the const keyword.
constructor () {}
public doSomething () {
if (condition is true) {
//do the needful
}
else
{
this.result = this.CONSTANT; // NO ERROR
}
}
}
Question1: why the class member does not have the const keyword in typescript?
问题 1:为什么 class 成员在 typescript 中没有 const 关键字?
Question2: When I use
问题2:当我使用
static readonly CONSTANT = 'constant';
and assign it in
并将其分配给
this.result = this.CONSTANT;
it displays error. why so?
它显示错误。为什么这样?
I have followed this post How to implement class constants in typescript?but don't get the answer why typescript is displaying this kind of error with const
keyword.
我已经关注了这篇文章如何在打字稿中实现类常量?但没有得到答案为什么打字稿用const
关键字显示这种错误。
回答by Pac0
Question1:why the class member does not have the const keyword in typescript?
问题1:为什么类成员在打字稿中没有const关键字?
By design. Among other reasons, because EcmaScript6 doesn't either.
按设计。除其他原因外,因为 EcmaScript6也没有.
This question is specifically answered here : 'const' keyword in TypeScript
这个问题在这里专门回答:TypeScript中的'const'关键字
Question2:When I use
static readonly CONSTANT = 'constant';
and assign it in
this.result = this.CONSTANT;
it displays error. why so?
问题2:当我使用
static readonly CONSTANT = 'constant';
并将其分配给
this.result = this.CONSTANT;
它显示错误。为什么这样?
If you use static
, then you can't refer to your variable with this
, but with the the name of the class !
如果你使用static
,那么你不能用 来引用你的变量this
,而是用类的名称!
export class Constant{
let result : string;
static readonly CONSTANT = 'constant';
constructor(){}
public doSomething(){
if( condition is true){
//do the needful
}
else
{
this.result = Constant.CONSTANT;
}
}
}
Why ? Because this
refers to the instance of the class to which the field / method belongs. For a static variable / method, it doesn't belong to any instance, but to the class itself (quickly simplified)
为什么 ?因为this
是指字段/方法所属的类的实例。对于静态变量/方法,它不属于任何实例,而是属于类本身(快速简化)