Open
Description
🐛 Bug Report
immer allows modification of readonly
properties of nested class instances that are not marked as immerable
. This seems dangerous to me. Just like immer does not allow direct modification of class instances that are not marked as immerable
, an exception should be thrown. Even better, the types should not allow this.
import { immerable, produce } from "immer";
class Address {
constructor(public readonly streetName: string) {
this.streetName = streetName;
}
}
class ImmerableAddress {
[immerable] = true;
constructor(public readonly streetName: string) {
this.streetName = streetName;
}
}
class ImmerablePerson {
[immerable] = true;
constructor(public readonly address: Address) {
this.address = address;
}
}
describe("immer", () => {
const immerableAddress = new ImmerableAddress("foo");
it("works fine with immerable nested class instance", () => {
const produced = produce(new ImmerablePerson(immerableAddress), (draft) => {
draft.address.streetName = "bar";
});
expect(produced.address.streetName).toBe("bar");
expect(produced.address).toBeInstanceOf(ImmerableAddress);
expect(produced.address).not.toBe(immerableAddress);
});
const address = new Address("foo");
it("allows illegal modification of non-immerable nested class instance", () => {
const produced = produce(new ImmerablePerson(address), (draft) => {
draft.address.streetName = "bar"; // works unexpectedly
});
expect(produced.address.streetName).toBe("bar");
expect(produced.address).toBeInstanceOf(Address);
expect(produced.address).toBe(address);
});
});
Link to repro
Environment
Immer 10.1.1
Metadata
Metadata
Assignees
Labels
No labels
Activity