typescript.md
This file
Path
docs/typescript.md
130 lines · 4.2 KiB · Markdown
Last changed by
docs: fix video player scrolling on chromeRachid Oussanaabefore adoption6397409
History of this fileTake it
Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 1–8why, one step back1---2id: typescript3title: Using TypeScript or Flow4sidebar_label: TypeScript / Flow5---67<div id="codefund"><!-- fallback content --></div>8Added egghead.io video embedsMichel Weststratebefore adoptiona866760
lines 9–12why, one step back9<details>10 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 12: Immer + TypeScript</summary>11 <br>12 <div style="padding:5px;">docs: fix video player scrolling on chromeRachid Oussanaabefore adoption6397409
line 13why, one step back13 <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 14–17why, one step back14 </div>15 <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>16</details>17Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 18–66why, one step back18The 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.1920The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:2122```ts23import produce from "immer"2425interface State {26 readonly x: number27}2829// `x` cannot be modified here30const state: State = {31 x: 032}3334const newState = produce(state, draft => {35 // `x` can be modified here36 draft.x++37})3839// `newState.x` cannot be modified here40```4142This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!4344For 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:4546```ts47import produce, {Draft} from "immer"4849interface State {50 readonly x: number51}5253// `x` cannot be modified here54const state: State = {55 x: 056}5758const increment = produce((draft: Draft<State>, inc: number) => {59 // `x` can be modified here60 draft.x += inc61})6263const newState = increment(state, 2)64// `newState.x` cannot be modified here65```66docs: added TypeScript readonly types noteMichel Weststratebefore adoptiond3be40e
lines 67–68why, one step back67_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)_68feat: general typing improvements for TS 3.7 and upMichel Weststratebefore adoptionf930ce1
lines 69–125why, one step back69## Cast utilities7071The 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`.7273Sometimes this leads to practical conflicts. Take the following example:7475```typescript76type Todo = {readonly done: boolean}7778type State = {79 readonly finishedTodos: readonly Todo[]80 readonly unfinishedTodos: readonly Todo[]81}8283function markAllFinished(state: State) {84 produce(state, draft => {85 draft.finishedTodos = state.unfinishedTodos86 })87}88```8990This will generate the error:9192```93The type 'readonly Todo[]' is 'readonly' and cannot be assigned to the mutable type '{ done: boolean; }[]'94```9596The reason for this error is that we assing 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 `asDraft`:9798`draft.finishedTodos = castDraft(state.unfinishedTodos)` will make the error disappear.99100There 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.101102Tip: You can combine `castImmutable` with `produce` to type the return type of `produce` as something immutable, even when the original state was mutable:103104```typescript105// a mutable data structure106const baseState = {107 todos: [{108 done: false109 }]110}111112const nextState = castImmutable(produce(baseState, _draft => {}))113114// inferred type of nextState is now:115{116 readonly todos: ReadonlyArray<{117 readonly done: boolean118 }>119})120```121122## Compatibility123124**Note:** Immer v5.3+ supports TypeScript v3.7+ only.125Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 126–130why, one step back126**Note:** Immer v1.9+ supports TypeScript v3.1+ only.127128**Note:** Immer v3.0+ supports TypeScript v3.4+ only.129130**Note:** Flow support might be removed in future versions and we recommend TypeScript