Introduced `castDraft` / `castImmutable`, implements #486
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 4204af5 · Browse files · 4 files·+81 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+81 added−2 removed
- tests:+16 added−1 removed
- other:+65 added−1 removed
Provenance
- Commit
2d27f33- Tree
a955b8f- Author
Michel Weststrate <mweststrate@fb.com>- Committer
Michel Weststrate <mweststrate@fb.com>- Parent
4204af5
4 files changed+81 added−2 removed
modified:__tests__/draft.ts+16 added-1 removed
1 import {assert, _} from "spec.ts"2-import {Draft} from "../src/index"2+import produce, {Draft, Draft, castDraft} from "../src/index"3 4 // For checking if a type is assignable to its draft type (and vice versa)5 const toDraft: <T>(value: T) => Draft<T> = x => x as any6 const fromDraft: <T>(draft: Draft<T>) => T = x => x as any295 unmodified lines302 }303 304 expect(true).toBe(true)305 })306+307+test("asDraft", () => {308+ type Todo = {readonly done: boolean}309+310+ type State = {311+ readonly finishedTodos: ReadonlyArray<Todo>312+ readonly unfinishedTodos: ReadonlyArray<Todo>313+ }314+315+ function markAllFinished(state: State) {316+ produce(state, draft => {317+ draft.finishedTodos = castDraft(state.unfinishedTodos)318+ })319+ }320+})modified:docs/api.md+2 added
6 unmodified lines7891011121314151627 unmodified lines6 unmodified lines
| Exported name | Description | Section || --- | --- | --- || `applyPatches` | Given a base state or draft, and a set of patches, applies the patches | [Patches](patches.md) || `castDraft` | Converts any immutable type to its mutable counterpart. This is just a cast and doesn't actually do anything. | [TypeScript](typescript.md) || `castImmutable` | Converts any mutable type to its immutable counterpart. This is just a cast and doesn't actually do anything. | [TypeScript](typescript.md) || `createDraft` | Given a base state, creates a mutable draft for which any modifications will be recorded | [Async](async.md) || `Draft<T>` | Exposed TypeScript type to convert an immutable type to a mutable type | [TypeScript](typescript.md) || `finishDraft` | Given an draft created using `createDraft`, seals the draft and produces and returns the next immutable state that captures all the changes | [Async](async.md) || `Immer` | constructor that can be used to create a second "immer" instance (exposing all APIs listed in this instance), that doesn't share its settings with global instance. Can also be used to attach further hooks that are triggered during object finalization, such as `onAssign`, `onDelete` and `onCopy`. | [See source](https://github.com/immerjs/immer/blob/cb1c6dd8a33073aaa0a4d881c94ec7ab1c1be7f6/src/immer.d.ts#L224-L233) |27 unmodified linesmodified:docs/typescript.md+37 added
64 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911064 unmodified lines```
_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)_
## Cast utilities
The 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`.
Sometimes this leads to practical conflicts. Take the following example:
```typescripttype Todo = {readonly done: boolean}
type State = { readonly finishedTodos: readonly Todo[] readonly unfinishedTodos: readonly Todo[]}
function markAllFinished(state: State) { produce(state, draft => { draft.finishedTodos = state.unfinishedTodos })}```
This will generate the error:
```The type 'readonly Todo[]' is 'readonly' and cannot be assigned to the mutable type '{ done: boolean; }[]'```
The 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`:
`draft.finishedTodos = castDraft(state.unfinishedTodos)` will make the error disappear.
There 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.
## Compatibility
**Note:** Immer v5.3+ supports TypeScript v3.7+ only.
**Note:** Immer v1.9+ supports TypeScript v3.1+ only.
**Note:** Immer v3.0+ supports TypeScript v3.4+ only.
**Note:** Flow support might be removed in future versions and we recommend TypeScriptmodified:src/index.ts+26 added-1 removed
1-import {IProduce, IProduceWithPatches, Immer} from "./internal"1+import {2+ IProduce,3+ IProduceWithPatches,4+ Immer,5+ Draft,6+ Immutable7+} from "./internal"8 9 export {10 Draft,11 Immutable,75 unmodified lines87 * changes that were made.88 */89 export const finishDraft = immer.finishDraft.bind(immer)90 91+/**92+ * This function is actually a no-op, but can be used to cast an immutable type93+ * to an draft type and make TypeScript happy94+ *95+ * @param value96+ */97+export function castDraft<T>(value: T): Draft<T> {98+ return value as any99+}100+101+/**102+ * This function is actually a no-op, but can be used to cast a mutable type103+ * to an immutable type and make TypeScript happy104+ * @param value105+ */106+export function castImmutable<T>(value: T): Immutable<T> {107+ return value as any108+}109+110 export {Immer}