假设我有一个内联类型
class Tmp {
#myreadonlystring /*:string*/ = "Some string";
}
我可以在这里使用实用程序类型
$ReadOnly
吗?
我试过了
#myreadonlystring /*:$ReadOnly<string>*/ = "Some string";
但是得到了
无法实例化 $ReadOnly,因为字符串 [1] 不是对象。 [非物体]
我不能在属性前面使用
+
,因为这是一个遗留项目,没有进行任何转译。
实用程序类型
$ReadOnly
仅针对对象类型而设计 - 提供的类型将被视为冻结。在您的情况下,您可以使用 getter 方法,而无需定义 setter 方法。它实际上并不会阻止直接重新分配,而是不会更改属性的值。
class Tmp {
#myreadonlystring = "Some string"
get myreadonlystring() {
return this.#myreadonlystring
}
}
const tmp = new Tmp()
console.log(tmp.myreadonlystring) // "Some string"
tmp.myreadonlystring = "foo"
console.log(tmp.myreadonlystring) // "Some string"