I have a class with a readonly attribute that I define inside a function
inside the constructor
, the compiler issues an error I do not know how to solve:
class TEST {
public readonly desc: string;
constructor() {
const compute = () => {
this.desc = "description"
};
}
}
The compiler says: "Cannot assign to "desc" because it is a readonly property"
but I thought that assigning the property inside the constructor will avoid this kind of errors.
Is it possible or do I have to change implementation?
You will need a type assertion to get around it, the safest way it to use a mapped type that removes readonly
from the type:
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
class TEST {
public readonly desc!: string;
constructor() {
const compute = () => {
(this as Mutable<TEST>).desc = "description"
};
}
}
readonly
is a rather weak modifier, so if you don't mind passing in this
as a parameter, you can avoid the assertion:
class TEST {
public readonly desc!: string;
constructor() {
const compute = (target: Mutable<TEST>) => {
target.desc = "description"
};
compute(this)// works fine and not just because we are in teh constructor
}
}