【问题标题】:Why can't we define a const field in TypeScript class, and why static readonly is not working?为什么我们不能在 TypeScript 类中定义一个 const 字段,为什么静态只读不起作用?
【发布时间】:2018-03-28 19:15:06
【问题描述】:

我想在我的程序中使用 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?,但不明白为什么打字稿会用const关键字显示这种错误。

【问题讨论】:

    标签: typescript constants


    【解决方案1】:

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

    按设计。除其他原因外,因为 EcmaScript6 doesn't either。

    这里专门回答了这个问题:'const' keyword in TypeScript


    问题 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指的是字段/方法所属的类的实例。对于静态变量/方法,它不属于任何实例,而是属于类本身(快速简化)

    【讨论】:

      猜你喜欢
      • 2017-12-08
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 2010-09-27
      • 2012-06-11
      • 2012-04-04
      • 2016-05-10
      相关资源
      最近更新 更多