1

I have a class with a readonly attribute that I define inside a functioninside 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?

jackssrt
  • 364
  • 1
  • 2
  • 16
Plastic
  • 9,874
  • 6
  • 32
  • 53
  • But you are not assigning in the constructor, you are assigning in an arrow function that just happens to be defined in the constructor .. – Titian Cernicova-Dragomir Jan 04 '19 at 15:11
  • Exactly! is there a way to get around this limitation? because I would like to declare the variable "readonly" but its value comes from the result of a function ... – Plastic Jan 04 '19 at 15:13
  • It would be nice to know who downvote, but most important WHY :) – Plastic Sep 05 '19 at 10:53

1 Answers1

2

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
    }
}
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357