Immer modifies `readonly` properties of nested instances that are not immerable
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 29k
- Forks
- 881
- PR merge metrics
- No merged PRs in 30d
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
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked CodeSandbox reproduction and inspect the existing handling of non-immerable class instances and readonly typing. Done means the nested Address case is rejected consistently, with regression coverage for the runtime and/or type behavior; the issue does not choose between those outcomes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, typescript
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100