Skip to content
Myr

typescript.md

This file

Path

docs/typescript.md

132 lines · 4.3 KiB · Markdown

Last changed by

docs: updated sponsor linksMichel Weststratebefore adoptionf97d037

History of this file

Take it

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 1–6why, one step back
1---
2id: typescript3title: Using TypeScript or Flow4sidebar_label: TypeScript / Flow5---6

docs: updated sponsor linksMichel Weststratebefore adoptionf97d037

lines 7–9why, one step back
7<center>
8<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>9</center>

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

line 10why, one step back
10

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 11–14why, one step back
11<details>
12 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 12: Immer + TypeScript</summary>13 <br>14 <div style="padding:5px;">

docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585

line 15why, one step back
15 <iframe style="border: none;" width=760 height=427 scrolling="no" src="https://egghead.io/lessons/react-type-immutable-immer-data-with-typescript/embed" ></iframe>

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 16–19why, one step back
16 </div>
17 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-type-immutable-immer-data-with-typescript">Hosted on egghead.io</a>18</details>19

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 20–43why, one step back
20The 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.
2122The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:2324```ts25import produce from "immer"2627interface State {28 readonly x: number29}3031// `x` cannot be modified here32const state: State = {33 x: 034}3536const newState = produce(state, draft => {37 // `x` can be modified here38 draft.x++39})4041// `newState.x` cannot be modified here42```43

Merge pull request #530 from cuongdevjs/improve-docsMichel Weststratebefore adoptionab3b8d0

line 44why, one step back
44This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`!

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 45–68why, one step back
45
46For 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:4748```ts49import produce, {Draft} from "immer"5051interface State {52 readonly x: number53}5455// `x` cannot be modified here56const state: State = {57 x: 058}5960const increment = produce((draft: Draft<State>, inc: number) => {61 // `x` can be modified here62 draft.x += inc63})6465const newState = increment(state, 2)66// `newState.x` cannot be modified here67```68

docs: added TypeScript readonly types noteMichel Weststratebefore adoptiond3be40e

lines 69–70why, one step back
69_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)_
70

feat: general typing improvements for TS 3.7 and upMichel Weststratebefore adoptionf930ce1

lines 71–97why, one step back
71## Cast utilities
7273The 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`.7475Sometimes this leads to practical conflicts. Take the following example:7677```typescript78type Todo = {readonly done: boolean}7980type State = {81 readonly finishedTodos: readonly Todo[]82 readonly unfinishedTodos: readonly Todo[]83}8485function markAllFinished(state: State) {86 produce(state, draft => {87 draft.finishedTodos = state.unfinishedTodos88 })89}90```9192This will generate the error:9394```95The type 'readonly Todo[]' is 'readonly' and cannot be assigned to the mutable type '{ done: boolean; }[]'96```97

Merge pull request #531 from denis-sokolov/as-draft-namingMichel Weststratebefore adoptionc7e9de8

line 98why, one step back
98The 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`:

feat: general typing improvements for TS 3.7 and upMichel Weststratebefore adoptionf930ce1

lines 99–127why, one step back
99
100`draft.finishedTodos = castDraft(state.unfinishedTodos)` will make the error disappear.101102There 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.103104Tip: You can combine `castImmutable` with `produce` to type the return type of `produce` as something immutable, even when the original state was mutable:105106```typescript107// a mutable data structure108const baseState = {109 todos: [{110 done: false111 }]112}113114const nextState = castImmutable(produce(baseState, _draft => {}))115116// inferred type of nextState is now:117{118 readonly todos: ReadonlyArray<{119 readonly done: boolean120 }>121})122```123124## Compatibility125126**Note:** Immer v5.3+ supports TypeScript v3.7+ only.127

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

line 128why, one step back
128**Note:** Immer v3.0+ supports TypeScript v3.4+ only.

Merge pull request #612 from anyxem/patch-1Michel Weststratebefore adoptiond4a77b9

lines 129–130why, one step back
129
130**Note:** Immer v1.9+ supports TypeScript v3.1+ only.

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 131–132why, one step back
131
132**Note:** Flow support might be removed in future versions and we recommend TypeScript