From 677becc9079da49021c0de72eb873a7191815209 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Burzy=C5=84ski?= Date: Sat, 9 Mar 2024 12:00:28 +0100 Subject: [PATCH] Limit the change to `applyPatches` --- __tests__/produce.ts | 17 ++++++++++++++++- src/core/immerClass.ts | 16 ++++++---------- src/types/types-external.ts | 7 ++----- 3 files changed, 24 insertions(+), 16 deletions(-) diff --git a/__tests__/produce.ts b/__tests__/produce.ts index 22f0a318..f9093688 100644 --- a/__tests__/produce.ts +++ b/__tests__/produce.ts @@ -8,7 +8,8 @@ import { Immutable, Immer, enableMapSet, - enablePatches + enablePatches, + produceWithPatches } from "../src/immer" enableMapSet() @@ -162,6 +163,20 @@ it("can apply patches", () => { expect(applyPatches({}, patches)).toEqual({x: 4}) }) +it("can apply readonly patches", () => { + const [, patches]: readonly [ + { + x: number + }, + readonly Patch[], + readonly Patch[] + ] = produceWithPatches({x: 3}, d => { + d.x++ + }) + + expect(applyPatches({}, patches)).toEqual({x: 4}) +}) + describe("curried producer", () => { it("supports rest parameters", () => { type State = {readonly a: 1} diff --git a/src/core/immerClass.ts b/src/core/immerClass.ts index ed04e9f2..b7ac51b3 100644 --- a/src/core/immerClass.ts +++ b/src/core/immerClass.ts @@ -120,15 +120,11 @@ export class Immer implements ProducersFns { this.produceWithPatches(state, (draft: any) => base(draft, ...args)) } - let patches: readonly Patch[], inversePatches: readonly Patch[] - const result = this.produce( - base, - recipe, - (p: readonly Patch[], ip: readonly Patch[]) => { - patches = p - inversePatches = ip - } - ) + let patches: Patch[], inversePatches: Patch[] + const result = this.produce(base, recipe, (p: Patch[], ip: Patch[]) => { + patches = p + inversePatches = ip + }) return [result, patches!, inversePatches!] } @@ -171,7 +167,7 @@ export class Immer implements ProducersFns { this.useStrictShallowCopy_ = value } - applyPatches(base: T, patches: Patch[]): T { + applyPatches(base: T, patches: readonly Patch[]): T { // If a patch replaces the entire state, take that replacement as base // before applying patches let i: number diff --git a/src/types/types-external.ts b/src/types/types-external.ts index 717df9b4..8bb44aba 100644 --- a/src/types/types-external.ts +++ b/src/types/types-external.ts @@ -68,10 +68,7 @@ export interface Patch { value?: any } -export type PatchListener = ( - patches: readonly Patch[], - inversePatches: readonly Patch[] -) => void +export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void /** Converts `nothing` into `undefined` */ type FromNothing = T extends typeof NOTHING ? undefined : T @@ -84,7 +81,7 @@ export type Produced = Return extends void /** * Utility types */ -type PatchesTuple = readonly [T, readonly Patch[], readonly Patch[]] +type PatchesTuple = readonly [T, Patch[], Patch[]] type ValidRecipeReturnType = | State