You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -64,6 +63,67 @@ This ensures that the only place you can modify your state is in your produce ca
64
63
2. You can use the utility type `Immutable` to recursively make an entire type tree read-only, e.g.: `type ReadonlyState = Immutable<State>`.
65
64
3. 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.
66
65
66
+
## Typing reusable recipes
67
+
68
+
If you want to pass a recipe callback around, you can type it using `Draft` and allow either `void` or a replacement state as the return value.
69
+
70
+
```ts
71
+
import {produce} from"immer"
72
+
importtype {Draft} from"immer"
73
+
74
+
typeRecipe<S> = (draft:Draft<S>) =>void|S
75
+
76
+
function updateState<S>(
77
+
setState: (updater: (prev:S) =>S) =>void,
78
+
recipe:Recipe<S>
79
+
) {
80
+
setState(prev=>produce(prev, recipe))
81
+
}
82
+
```
83
+
84
+
### React example
85
+
86
+
A common usage in React is to wrap `setState` with `produce` so callers can provide a typed recipe.
We 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:
0 commit comments