为什么我们不能在TypeScript类中定义常量字段,而静态只读属性却无效?

17

我想在我的程序中使用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: 为什么在TypeScript中,类成员没有const关键字?

问题2: 当我使用

static readonly CONSTANT = 'constant';

并将其分配

this.result = this.CONSTANT;

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

我已经遵循了这篇文章 How to implement class constants in typescript?,但是不知道为什么 TypeScript 使用 const 关键字时会出现这种错误。

1个回答

29

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

这是设计原则。除了其他原因外,因为EcmaScript6也没有

这个问题在这里得到了具体的回答:TypeScript中的'const'关键字


如果你使用了 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}}指的是字段/方法所属类的实例。对于静态变量/方法,它不属于任何实例,而是属于类本身(简单来说)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接