immerjs / immerjs/immer

Issue to index generic record with generic key value in recipe due to draft wrapper

Open
#1,135 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
29k
Forks
881
PR merge metrics
No merged PRs in 30d

Description

🐛 Bug Report

Using generic function arguments around produce causes type issues. Its probably best explained with an example (link to CodeSandbox below):

enum Foo {
  One,
  Two,
}

type Bar<F extends Foo> = Readonly<Record<F, number>>;

function modifyBar<F extends Foo>(bar: Bar<F>, foo: F, value: number): Bar<F> {
  return produce(bar, (draft) => {
    draft[foo] = value; // <-- Issue here
  });
}

The type error at the marked line is then: Type 'F' cannot be used to index type 'Draft<Readonly<Record<F, number>>>'.
A current workaround is to make the type Bar actually mutable (i.e. remove the Readonly wrapper) and then manually cast the recipe like (draft: Bar<F>) => { /* ... */ }. Both do not feel good or are not possible for the production circumstances.

Are there any alternatives to solve this properly?

Link to repro

Link to CodeSandbox

To Reproduce

Just inspect the error shown in the code editor.

Observed behavior

Type error that correct key type can't be used to index a Record wrapped as Draft.

Expected behavior

No type error and the produce just works as without a recipe.

Environment

We only accept bug reports against the latest Immer version.

  • Immer version: v10.1.1
  • I filed this report against the latest version of Immer
  • Occurs with setUseProxies(true) (I don't know how to apply this, sorry)
  • Occurs with setUseProxies(false) (ES5 only)

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked CodeSandbox at src/index.ts and reproduce the error on the draft[foo] assignment using Immer v10.1.1. Trace the TypeScript types involved in produce, Draft, and the readonly generic Record. Done means the generic readonly Record example type-checks without a manual cast while preserving the expected produce behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
developer-experience
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.