Skip to content
Myr

typescript.mdx

This file

Path

website/docs/typescript.mdx

210 lines · 6.8 KiB

Last changed by

docs: Fix typo (#862)ragheed-affasbefore adoption4e062c4

History of this file

Take it

1---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`.5960## Best practices61621. Always define your states as `readonly` as much as possible. This best reflects the mental model and reality, since Immer will freeze all its returned values.632. You can use the utility type `Immutable` to recursively make an entire type tree read-only, e.g.: `type ReadonlyState = Immutable<State>`.643. Immer won't automatically wrap all returned types in `Immutable` if the original type of the input state wasn't immutable. This is to make sure it doesn't break code bases that don't use immutable types.6566## Tips for curried producers6768We try to inference as much as possible. So if a curried producer is created and directly passed to another function, we can infer the type from there. This works well with for example React:6970```typescript71import {Immutable, produce} from "immer"7273type Todo = Immutable<{74	title: string75	done: boolean76}>7778// later...7980const [todo, setTodo] = useState<Todo>({81	title: "test",82	done: true83})8485// later...8687setTodo(88	produce(draft => {89		// draft will be strongly typed and mutable!90		draft.done = !draft.done91	})92)93```9495When a curried producer isn't passed directly somewhere else, Immer can infer the state type from the draft argument. For example when doing the following:9697```typescript98// See below for a better solution!99100const toggler = produce((draft: Draft<Todo>) => {101	draft.done = !draft.done102})103104// typeof toggler = (state: Immutable<Todo>) => Writable<Todo>105```106107Note that we did wrap the `Todo` type of the `draft` argument with `Draft`, because `Todo` is a readonly type. For non-readonly types this isn't needed.108109For the returned curried function, `toggler`, We will _narrow_ the _input_ type to `Immutable<Todo>`, so that even though `Todo` is a mutable type, we will still accept an immutable todo as input argument to `toggler`.110111In contrast, Immer will _widen_ the _output_ type of the curried function to `Writable<Todo>`, to make sure it's output state is also assignable to variables that are not explictly typed to be immutable.112113This type narrowing / widening behavior might be unwelcome, maybe even for the simple reason that it results in quite noisy types. So we recommend to specify the generic state type for curried producers instead, in cases where it cannot be inferred directly, like `toggler` above. By doing so the automatic output widening / input narrowing will be skipped. However, the `draft` argument itself will still be inferred to be a writable `Draft<Todo>`:114115```typescript116const toggler = produce<Todo>(draft => {117	draft.done = !draft.done118})119120// typeof toggler = (state: Todo) => Todo121```122123However, in case the curried producer is defined with an initial state, Immer can infer the state type from the initial state, so in that case the generic doesn't need to be specified either:124125```typescript126const state0: Todo = {127	title: "test",128	done: false129}130131// No type annotations needed, since we can infer from state0.132const toggler = produce(draft => {133	draft.done = !draft.done134}, state0)135136// typeof toggler = (state: Todo) => Todo137```138139In case the toggler has no initial state, and it has curried arguments, and you set the state generic explicitly, then type of any additional arguments should be defined explicitly as a tuple type as well:140141```typescript142const toggler = produce<Todo, [boolean]>((draft, newState) => {143	draft.done = newState144})145146// typeof toggler = (state: Todo, newState: boolean) => Todo147```148149## Cast utilities150151The 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`.152153Sometimes this leads to practical conflicts. Take the following example:154155```typescript156type Todo = {readonly done: boolean}157158type State = {159	readonly finishedTodos: readonly Todo[]160	readonly unfinishedTodos: readonly Todo[]161}162163function markAllFinished(state: State) {164	produce(state, draft => {165		draft.finishedTodos = state.unfinishedTodos166	})167}168```169170This will generate the error:171172```173The type 'readonly Todo[]' is 'readonly' and cannot be assigned to the mutable type '{ done: boolean; }[]'174```175176The 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`:177178`draft.finishedTodos = castDraft(state.unfinishedTodos)` will make the error disappear.179180There 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.181182Tip: You can combine `castImmutable` with `produce` to type the return type of `produce` as something immutable, even when the original state was mutable:183184```typescript185// a mutable data structure186const baseState = {187	todos: [{188		done: false189	}]190}191192const nextState = castImmutable(produce(baseState, _draft => {}))193194// inferred type of nextState is now:195{196	readonly todos: ReadonlyArray<{197		readonly done: boolean198	}>199})200```201202## Compatibility203204**Note:** Immer v5.3+ supports TypeScript v3.7+ only.205206**Note:** Immer v3.0+ supports TypeScript v3.4+ only.207208**Note:** Immer v1.9+ supports TypeScript v3.1+ only.209210**Note:** Flow support might be removed in future versions and we recommend TypeScript