typescript.mdx
This file
Path
website/docs/typescript.mdx
146 lines · 4.2 KiB
Last changed by
docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
History of this fileTake it
docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 1–146why, one step back1---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`!5960For curried reducers, the type is inferred from the first argument of recipe function, so make sure to type it. The `Draft` utility type can be used if the state argument type is immutable:6162```ts63import produce, {Draft} from "immer"6465interface State {66 readonly x: number67}6869// `x` cannot be modified here70const state: State = {71 x: 072}7374const increment = produce((draft: Draft<State>, inc: number) => {75 // `x` can be modified here76 draft.x += inc77})7879const newState = increment(state, 2)80// `newState.x` cannot be modified here81```8283_Note: Since TypeScript support for recursive types is limited, and there is no co- contravariance, it might the easiest to not type your state as `readonly` (Immer will still protect against accidental mutations)_8485## Cast utilities8687The 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`.8889Sometimes this leads to practical conflicts. Take the following example:9091```typescript92type Todo = {readonly done: boolean}9394type State = {95 readonly finishedTodos: readonly Todo[]96 readonly unfinishedTodos: readonly Todo[]97}9899function markAllFinished(state: State) {100 produce(state, draft => {101 draft.finishedTodos = state.unfinishedTodos102 })103}104```105106This will generate the error:107108```109The type 'readonly Todo[]' is 'readonly' and cannot be assigned to the mutable type '{ done: boolean; }[]'110```111112The 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`:113114`draft.finishedTodos = castDraft(state.unfinishedTodos)` will make the error disappear.115116There 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.117118Tip: You can combine `castImmutable` with `produce` to type the return type of `produce` as something immutable, even when the original state was mutable:119120```typescript121// a mutable data structure122const baseState = {123 todos: [{124 done: false125 }]126}127128const nextState = castImmutable(produce(baseState, _draft => {}))129130// inferred type of nextState is now:131{132 readonly todos: ReadonlyArray<{133 readonly done: boolean134 }>135})136```137138## Compatibility139140**Note:** Immer v5.3+ supports TypeScript v3.7+ only.141142**Note:** Immer v3.0+ supports TypeScript v3.4+ only.143144**Note:** Immer v1.9+ supports TypeScript v3.1+ only.145146**Note:** Flow support might be removed in future versions and we recommend TypeScript