1

I have just came across this super simple example where typescript would not guard enough and would let readonly object been passed where mutable is expected.

Following compiles in TS 5.1.6 (and all other version I tested):

type ReadonlyObj = {
    readonly x:number;
}

type MutableObj = {
    x:number;
}

function mutate(mutableObj:MutableObj) {
  mutableObj.x = 1;
}

const readonlyObj:ReadonlyObj = {x:0};
mutate(readonlyObj);

Should this be reported, or it is intended? If intended, how can I make sure my readonly object (and its parameters) is (compile time) protected from being mutated? Is there any compiler flag to define?

1
  • 1
    There's no great way to deal with this; see the linked questions and answers for explanations. Commented Jul 20, 2023 at 14:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.