Skip to content
Myr

typescript.md

This file

Path

docs/typescript.md

62 lines · 1.6 KiB · Markdown

Last changed by

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

History of this file

Take it

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 1–62why, one step back
1---
2id: typescript3title: Using TypeScript or Flow4sidebar_label: TypeScript / Flow5---67<div id="codefund"><!-- fallback content --></div>89The 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.1011The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:1213```ts14import produce from "immer"1516interface State {17 readonly x: number18}1920// `x` cannot be modified here21const state: State = {22 x: 023}2425const newState = produce(state, draft => {26 // `x` can be modified here27 draft.x++28})2930// `newState.x` cannot be modified here31```3233This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!3435For 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:3637```ts38import produce, {Draft} from "immer"3940interface State {41 readonly x: number42}4344// `x` cannot be modified here45const state: State = {46 x: 047}4849const increment = produce((draft: Draft<State>, inc: number) => {50 // `x` can be modified here51 draft.x += inc52})5354const newState = increment(state, 2)55// `newState.x` cannot be modified here56```5758**Note:** Immer v1.9+ supports TypeScript v3.1+ only.5960**Note:** Immer v3.0+ supports TypeScript v3.4+ only.6162**Note:** Flow support might be removed in future versions and we recommend TypeScript