Skip to content
Myr

typescript.md

This file

Path

docs/typescript.md

71 lines · 2.1 KiB · Markdown

Last changed by

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

History of this file

Take it

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 1–8why, one step back
1---
2id: typescript3title: Using TypeScript or Flow4sidebar_label: TypeScript / Flow5---67<div id="codefund"><!-- fallback content --></div>8

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 9–17why, one step back
9<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;">13 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-type-immutable-immer-data-with-typescript/embed" ></iframe>14 </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>17

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 18–71why, one step back
18The 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```6667**Note:** Immer v1.9+ supports TypeScript v3.1+ only.6869**Note:** Immer v3.0+ supports TypeScript v3.4+ only.7071**Note:** Flow support might be removed in future versions and we recommend TypeScript