typescript.mdx
This file
Path
website/docs/typescript.mdx
271 lines · 8.0 KiB
Last changed by
docs: add typed custom produce function (#1239)Dean Kerrbefore adoption955c5f5
History of this fileTake it
1---2id: typescript3title: Using TypeScript or Flow4sidebar_label: TypeScript / Flow5---67<center>8 <div9 data-ea-publisher="immerjs"10 data-ea-type="image"11 className="horizontal bordered"12 ></div>13</center> <details>14 <summary className="egghead-summary">15 egghead.io lesson 12: Immer + TypeScript16 </summary>17 <br />18 <div>19 <iframe20 width="760"21 height="427"22 scrolling="no"23 src="https://egghead.io/lessons/react-type-immutable-immer-data-with-typescript/embed"24 ></iframe>25 </div>26 <a27 className="egghead-link"28 href="https://egghead.io/lessons/react-type-immutable-immer-data-with-typescript"29 >30 Hosted on egghead.io31 </a>32</details>3334The Immer package ships with type definitions inside the package, which should be picked up by TypeScript and Flow out of the box and without further configuration.3536The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:3738```ts39import {produce} from "immer"4041interface State {42 readonly x: number43}4445// `x` cannot be modified here46const state: State = {47 x: 048}4950const newState = produce(state, draft => {51 // `x` can be modified here52 draft.x++53})5455// `newState.x` cannot be modified here56```5758This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`.5960## Best practices61621. Always define your states as `readonly` as much as possible. This best reflects the mental model and reality, since Immer will freeze all its returned values.632. You can use the utility type `Immutable` to recursively make an entire type tree read-only, e.g.: `type ReadonlyState = Immutable<State>`.643. Immer won't automatically wrap all returned types in `Immutable` if the original type of the input state wasn't immutable. This is to make sure it doesn't break code bases that don't use immutable types.6566## Typing reusable recipes6768If you want to pass a recipe callback around, you can type it using `Draft` and allow either `void` or a replacement state as the return value.6970```ts71import {produce} from "immer"72import type {Draft} from "immer"7374type Recipe<S> = (draft: Draft<S>) => void | S7576function updateState<S>(77 setState: (updater: (prev: S) => S) => void,78 recipe: Recipe<S>79) {80 setState(prev => produce(prev, recipe))81}82```8384### React example8586A common usage in React is to wrap `setState` with `produce` so callers can provide a typed recipe.8788```tsx89import {produce} from "immer"90import type {Draft} from "immer"91import {useCallback, useState} from "react"9293type State = {94 foo: string95 bar: string96}9798const initialState: State = {99 foo: "",100 bar: ""101}102103type Recipe = (draft: Draft<State>) => void | State104105export function Example() {106 const [state, setState] = useState<State>(initialState)107108 const updateState = useCallback((recipe: Recipe) => {109 setState(prev => produce(prev, recipe))110 }, [])111112 return (113 <button114 onClick={() => {115 updateState(draft => {116 draft.foo = "Muffin Man" // this recipe is typed117 })118 }}119 type="button"120 >121 Hello {state.foo}122 </button>123 )124}125```126127## Tips for curried producers128129We try to inference as much as possible. So if a curried producer is created and directly passed to another function, we can infer the type from there. This works well with for example React:130131```typescript132import {Immutable, produce} from "immer"133134type Todo = Immutable<{135 title: string136 done: boolean137}>138139// later...140141const [todo, setTodo] = useState<Todo>({142 title: "test",143 done: true144})145146// later...147148setTodo(149 produce(draft => {150 // draft will be strongly typed and mutable!151 draft.done = !draft.done152 })153)154```155156When a curried producer isn't passed directly somewhere else, Immer can infer the state type from the draft argument. For example when doing the following:157158```typescript159// See below for a better solution!160161const toggler = produce((draft: Draft<Todo>) => {162 draft.done = !draft.done163})164165// typeof toggler = (state: Immutable<Todo>) => Writable<Todo>166```167168Note that we did wrap the `Todo` type of the `draft` argument with `Draft`, because `Todo` is a readonly type. For non-readonly types this isn't needed.169170For the returned curried function, `toggler`, We will _narrow_ the _input_ type to `Immutable<Todo>`, so that even though `Todo` is a mutable type, we will still accept an immutable todo as input argument to `toggler`.171172In contrast, Immer will _widen_ the _output_ type of the curried function to `Writable<Todo>`, to make sure it's output state is also assignable to variables that are not explicitly typed to be immutable.173174This type narrowing / widening behavior might be unwelcome, maybe even for the simple reason that it results in quite noisy types. So we recommend to specify the generic state type for curried producers instead, in cases where it cannot be inferred directly, like `toggler` above. By doing so the automatic output widening / input narrowing will be skipped. However, the `draft` argument itself will still be inferred to be a writable `Draft<Todo>`:175176```typescript177const toggler = produce<Todo>(draft => {178 draft.done = !draft.done179})180181// typeof toggler = (state: Todo) => Todo182```183184However, in case the curried producer is defined with an initial state, Immer can infer the state type from the initial state, so in that case the generic doesn't need to be specified either:185186```typescript187const state0: Todo = {188 title: "test",189 done: false190}191192// No type annotations needed, since we can infer from state0.193const toggler = produce(draft => {194 draft.done = !draft.done195}, state0)196197// typeof toggler = (state: Todo) => Todo198```199200In case the toggler has no initial state, and it has curried arguments, and you set the state generic explicitly, then type of any additional arguments should be defined explicitly as a tuple type as well:201202```typescript203const toggler = produce<Todo, [boolean]>((draft, newState) => {204 draft.done = newState205})206207// typeof toggler = (state: Todo, newState: boolean) => Todo208```209210## Cast utilities211212The types inside and outside a `produce` can be conceptually the same, but from a practical perspective different. For example, the `State` in the examples above should be considered immutable outside `produce`, but mutable inside `produce`.213214Sometimes this leads to practical conflicts. Take the following example:215216```typescript217type Todo = {readonly done: boolean}218219type State = {220 readonly finishedTodos: readonly Todo[]221 readonly unfinishedTodos: readonly Todo[]222}223224function markAllFinished(state: State) {225 produce(state, draft => {226 draft.finishedTodos = state.unfinishedTodos227 })228}229```230231This will generate the error:232233```234The type 'readonly Todo[]' is 'readonly' and cannot be assigned to the mutable type '{ done: boolean; }[]'235```236237The reason for this error is that we assign our read only, immutable array to our draft, which expects a mutable type, with methods like `.push` etc etc. As far as TS is concerned, those are not exposed from our original `State`. To hint TypeScript that we want to upcast the collection here to a mutable array for draft purposes, we can use the utility `castDraft`:238239`draft.finishedTodos = castDraft(state.unfinishedTodos)` will make the error disappear.240241There is also the utility `castImmutable`, in case you ever need to achieve the opposite. Note that these utilities are for all practical purposes no-ops, they will just return their original value.242243Tip: You can combine `castImmutable` with `produce` to type the return type of `produce` as something immutable, even when the original state was mutable:244245```typescript246// a mutable data structure247const baseState = {248 todos: [{249 done: false250 }]251}252253const nextState = castImmutable(produce(baseState, _draft => {}))254255// inferred type of nextState is now:256{257 readonly todos: ReadonlyArray<{258 readonly done: boolean259 }>260})261```262263## Compatibility264265**Note:** Immer v5.3+ supports TypeScript v3.7+ only.266267**Note:** Immer v3.0+ supports TypeScript v3.4+ only.268269**Note:** Immer v1.9+ supports TypeScript v3.1+ only.270271**Note:** Flow support might be removed in future versions and we recommend TypeScript