Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript: Cannot assign immutable state from payload to immutable writable draft #1127

Closed
1 of 3 tasks
gracicot opened this issue Jun 13, 2024 · 2 comments
Closed
1 of 3 tasks

Comments

@gracicot
Copy link

gracicot commented Jun 13, 2024

🐛 Bug Report

Immer exposes a Immutable helper type that deeply mark a type as readonly:

type A = Immutable<{ a: number }>;

const a: A = {
  a: 4
};

a.a = 5; // error, a.a is readonly

Immer also conveniently make it so that a WritableDraft<...> will let you assign to subobjects since immer will not mutate the original state, which is correct:

const a2 = produce(a, (draft) => {
  // draft is WritableDraft<Immutable<...>>
  draft.a = 5;
});

However, writable draft don't let an immutable value be assigned to another immutable value:

type B = Immutable<{ arr: number[] }>;

const b1: B = {
  arr: [1, 2, 3]
};

const b2: B = {
  arr: [4, 5, 6]
};

produce(b1, draft => {
  draft.arr = b2.arr;
});

This is technically correct as arr will be assigned to another mutable value

This issue arises a lot when you have an immutable state in redux, use a selector and send back a state in an action payload. When action payloads are immutable, this issue will trigger.

Link to repro

A bug report without a reproduction is not a bug report. Failing to follow this templately is likely to result in an immediate close & lock of the issue.

CodeSandbox demo

To Reproduce

Steps to reproduce the behavior:

type B = Immutable<{ arr: number[] }>;

const b1: B = {
  arr: [1, 2, 3]
};

const b2: B = {
  arr: [4, 5, 6]
};

produce(b1, draft => {
  draft.arr = b2.arr;
});

Observed behavior

Typescript refuses the code

Expected behavior

Typescript should accept the code

Environment

We only accept bug reports against the latest Immer version.

  • Immer version: 10.1.1
  • I filed this report against the latest version of Immer
  • Occurs with setUseProxies(true)
  • Occurs with setUseProxies(false) (ES5 only)
@mweststrate
Copy link
Collaborator

mweststrate commented Jun 13, 2024 via email

@gracicot
Copy link
Author

It seems castDraft works. It still would be nice to not need that so I'll keep the issue open. I'm the case it is completely unfixable, then maintainers can close this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants