gpt4 book ai didi

typescript - 为什么我们不能在 TypeScript 类中定义一个 const 字段,为什么 static readonly 不起作用?

转载 作者:搜寻专家 更新时间:2023-10-30 20:41:25 24 4
gpt4 key购买 nike

我想在我的程序中使用 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:为什么class member在typescript中没有const关键字?

问题2:当我使用

static readonly CONSTANT = 'constant';

并将其分配给

this.result = this.CONSTANT;

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

我已经关注了这篇文章How to implement class constants in typescript?但不知道为什么 typescript 使用 const 关键字显示这种错误。

最佳答案

Question1: why the class member does not have the const keyword in typescript?

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

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


Question2: When I use

static readonly CONSTANT = 'constant';and assign it in

this.result = this.CONSTANT;

it displays error. why so?

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

关于typescript - 为什么我们不能在 TypeScript 类中定义一个 const 字段,为什么 static readonly 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46784333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com