我有一个简单的类,我想给构造函数初始化的方法中的一个只读属性赋值,但是它说[ts] Cannot assign to 'readOnlyProperty' because it is a constant or a read-only property.
为什么我不能给这个属性赋值,即使我从构造函数调用process
?
样本代码:
class C {
readonly readOnlyProperty: string;
constructor(raw: string) {
this.process(raw);
}
process(raw: string) {
this.readOnlyProperty = raw; // [ts] Cannot assign to 'readOnlyProperty' because it is a constant or a read-only property.
}
}
5条答案
按热度按时间krugob8w1#
我通常使用以下解决方法:
现在您可以从类内部更改属性,从外部更改属性为
readonly
。这个解决方案的一个优点是你可以重构你的属性名,而不会产生错误,这就是为什么我不会使用这样的代码:
sulc1iza2#
您不应强制转换
this as any
,而应仅通过修改此属性来强制执行类型检查:eivgtgni3#
当你创建一个单独的函数来赋值时,这个单独的函数可以从其他地方使用,而不是从唯一的构造函数使用。编译器不会检查(对于一个公共函数,甚至不能检查)这个函数是否只从构造函数调用。所以错误。
无论如何,你有两种方法来赋值,一种是把你的独立函数的核心放到构造函数中,另一种是,会让你失去类型检查,所以不推荐,除非你真的知道你在做什么,将
this
转换成any
:nbysray54#
很老的问题,但我认为这仍然值得分享我通常是如何克服这个问题的。我倾向于返回你想从方法中设置的值,然后你仍然分离逻辑,同时保持只读,没有任何可以论证的非法旁路。
koaltpgm5#
试试看