为什么我们不能在TypeScript类中定义const字段,以及为什么静态readonly不起作用?

Adi*_*tya 5 const typescript

我想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
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

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

问题2:当我使用时

static readonly CONSTANT = 'constant';
Run Code Online (Sandbox Code Playgroud)

并分配

this.result = this.CONSTANT;
Run Code Online (Sandbox Code Playgroud)

它显示错误.为什么这样?

我已经按照这篇文章如何在typescript中实现类常量?但是没有得到答案为什么typescript用const关键字显示这种错误.

Pac*_*ac0 20

问题1:为什么类成员在typescript中没有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;
   }
}
}
Run Code Online (Sandbox Code Playgroud)

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