Say I have an inline type like
class Tmp {
#myreadonlystring /*:string*/ = "Some string";
}
Can I use the utility type $ReadOnly
somehow here?
I tried
#myreadonlystring /*:$ReadOnly<string>*/ = "Some string";
but got
Cannot instantiate $ReadOnly because string [1] is not an object. [not-an-object]
I can't use +
in front of the property, because this is a legacy project without any transpilation going on.
Utility type $ReadOnly
was designed for object types only - provided type will be treated as frozen. In your case, you can use getter method, without defining setter method. It doesn't actually prevents the direct reassignment, but instead doesn't change the value of a property.
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"