为什么我们不能在 TypeScript 类中定义一个 const 字段,为什么静态只读不起作用?



我想在我的程序中使用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
        }

    }
}

问题 1:为什么类成员在打字稿中没有 const 关键字?

问题2:当我使用

static readonly CONSTANT = 'constant';

并将其分配在

this.result = this.CONSTANT;

它显示错误。为什么会这样?

我已经关注了这篇文章 如何在打字稿中实现类常量? 但是不知道为什么打字稿会用const关键字显示这种错误。

问题 1:为什么类成员在打字稿中没有 const 关键字?

通过设计。除其他原因外,因为 EcmaScript6 也没有。

这个问题在这里得到了特别的回答:TypeScript 中的"const"关键字


问题2: 当我使用

static readonly CONSTANT = 'constant';并分配它

this.result = this.CONSTANT;

它显示错误。为什么会这样?

如果你使用 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;
   }
}
}

为什么?因为this是指字段/方法所属的类的实例。对于静态变量/方法,它不属于任何实例,而是属于类本身(快速简化)

最新更新