immerjs / immer

Create the next immutable state by mutating the current one

Home Page:https://immerjs.github.io/immer/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TypeScript Error with URL Assignment: 'URL' is not assignable to type 'WritableDraft<URL>'.

xpatrykk opened this issue Β· comments

πŸ› Bug Report

I am encountering an issue with the Immer library when trying to update an attribute with a URL type. TypeScript reports the following error:

Type 'URL' is not assignable to type 'WritableDraft<URL>'.
  Types of property 'searchParams' are incompatible.
    Type 'URLSearchParams' is missing the following properties from type 'Map<string, string | null>': clear, [Symbol.toStringTag]typescript(2322)

Here's an example of how the code is implemented:

const state = {
  anotherAttribute: "value",
  myUrlAttribute: new URL("https://example.com"),
};

produce(state, (draft) => {
  draft.myUrlAttribute = new URL("https://example.com");
});

Link to repro
You can find a live demonstration of the issue in this CodeSandbox link: https://codesandbox.io/p/sandbox/reverent-fog-yc4hq5

To Reproduce

  1. Define a state object with an attribute of type URL.
  2. Use the produce function to modify the URL attribute.
  3. TypeScript reports the error mentioned above.

Observed behavior
TypeScript reports an error when trying to assign a new URL object to a draft URL attribute within the produce function.

Expected behavior
I expect the URL attribute to be updated without any TypeScript errors.

Environment

  • Immer version: ^9.0.21
  • TypeScript version: 5.0.4
  • βœ… I filed this report against the latest version of Immer
  • ❌ Occurs with setUseProxies(true)
  • ❌ Occurs with setUseProxies(false) (ES5 only)

This function solves the problem. Thank you for the help. Wonderful library.