diff --git a/src/apply.ts b/src/apply.ts index c75f136..17b3761 100644 --- a/src/apply.ts +++ b/src/apply.ts @@ -1,5 +1,11 @@ import { Operation, DraftType } from './interface'; -import type { Draft, Options, Patches, ApplyMutableOptions } from './interface'; +import type { + Draft, + Patches, + ApplyMutableOptions, + ApplyOptions, + ApplyResult, +} from './interface'; import { deepClone, get, getType, isDraft, unescapePath } from './utils'; import { create } from './create'; @@ -24,16 +30,11 @@ import { create } from './create'; * expect(state).toEqual(apply(baseState, patches)); * ``` */ -export function apply( - state: T, - patches: Patches, - applyOptions?: - | Pick< - Options, - Exclude, 'enablePatches'> - > - | ApplyMutableOptions -) { +export function apply< + T extends object, + F extends boolean = false, + A extends ApplyOptions = ApplyOptions +>(state: T, patches: Patches, applyOptions?: A): ApplyResult { let i: number; for (i = patches.length - 1; i >= 0; i -= 1) { const { value, op, path } = patches[i]; @@ -127,17 +128,17 @@ export function apply( }; if ((applyOptions as ApplyMutableOptions)?.mutable) { mutate(state); - return; + return undefined as ApplyResult; } if (isDraft(state)) { if (applyOptions !== undefined) { throw new Error(`Cannot apply patches with options to a draft.`); } mutate(state as Draft); - return state; + return state as ApplyResult; } return create(state, mutate, { ...applyOptions, enablePatches: false, - }); + }) as any; } diff --git a/src/interface.ts b/src/interface.ts index 646fc61..58b83ad 100644 --- a/src/interface.ts +++ b/src/interface.ts @@ -197,3 +197,16 @@ export type Draft = T extends Primitive | AtomicObject : T extends object ? DraftedObject : T; + +export type ApplyOptions = + | Pick< + Options, + Exclude, 'enablePatches'> + > + | ApplyMutableOptions; + +export type ApplyResult< + T extends object, + F extends boolean = false, + A extends ApplyOptions = ApplyOptions +> = A extends { mutable: true } ? void : T; diff --git a/test/apply.test.ts b/test/apply.test.ts index 0fec6df..3d16aad 100644 --- a/test/apply.test.ts +++ b/test/apply.test.ts @@ -1305,16 +1305,6 @@ test('merge multiple patches', () => { enablePatches: true, } ); - console.log( - JSON.stringify( - { - patches, - inversePatches, - }, - null, - 2 - ) - ); const [state1, patches1, inversePatches1] = create( state, (draft) => { @@ -1390,8 +1380,13 @@ test('base - mutate', () => { }, ], }); + const nextState = apply(baseState, patches); + expect(nextState).toEqual({ a: { c: 2 } }); + expect(baseState).toEqual({ a: { c: 1 } }); + const result = apply(baseState, patches, { mutable: true, }); expect(baseState).toEqual({ a: { c: 2 } }); + expect(result).toBeUndefined(); });