How to use readonly arrays with Immer + TypeScript? (version 8 regression)

111 Views Asked by At

Consider the following short code snippet.

Immer seems to have a problem with readonly arrays, which doesn't make sense to me, because your state should always be immutable, which is the whole point of using immer in the first place.

Before Immer version 7, this pattern worked fine, but in Immer 8+, it throws an error. How do I work around this problem or structure my code in the correct way?

1

There are 1 best solutions below

0
On BEST ANSWER

You'll have to cast your state, like this -

import { Draft, castDraft } from "immer";

interface MyState {
  readonly mySubState: MySubState;
}

interface MySubState {
  readonly someString: string;
  readonly someStrings: readonly string[];
}

function getDefaultMySubState(): MySubState {
  return {
    someString: "foo",
    someStrings: ["foo", "bar"],
  }
}

function myReducerFunction(state: Draft<MyState>) {
  const mySubState = getDefaultMySubState();
  state.mySubState = castDraft(mySubState);
}

Here's a playground link and here's where you can read more about it.