Skip to content

Commit 182009b

Browse files
authored
fix: honor class-only shallow copy in Immer constructor (#1357)
1 parent 75a290e commit 182009b

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

‎__tests__/not-strict-copy.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
Immer,
23
immerable,
34
produce,
45
setUseStrictShallowCopy,
@@ -73,3 +74,29 @@ describe.each([true, false, "class_only" as const])(
7374
})
7475
}
7576
)
77+
78+
test("honors the constructor class_only shallow copy mode", () => {
79+
const immer = new Immer({useStrictShallowCopy: "class_only"})
80+
81+
class Example {
82+
[immerable] = true
83+
count = 0
84+
}
85+
86+
const instance = new Example()
87+
const plain = {count: 0}
88+
Object.defineProperty(instance, "hidden", {value: 42})
89+
Object.defineProperty(plain, "hidden", {value: 42})
90+
91+
const nextInstance = immer.produce(instance, draft => {
92+
draft.count++
93+
})
94+
const nextPlain = immer.produce(plain, draft => {
95+
draft.count++
96+
})
97+
98+
expect(Object.getOwnPropertyDescriptor(nextInstance, "hidden")?.value).toBe(
99+
42
100+
)
101+
expect(Object.hasOwn(nextPlain, "hidden")).toBe(false)
102+
})

‎src/core/immerClass.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,9 @@ export class Immer implements ProducersFns {
5555
useStrictIteration?: boolean
5656
}) {
5757
if (isBoolean(config?.autoFreeze)) this.setAutoFreeze(config!.autoFreeze)
58-
if (isBoolean(config?.useStrictShallowCopy))
59-
this.setUseStrictShallowCopy(config!.useStrictShallowCopy)
58+
const strictShallowCopy = config?.useStrictShallowCopy
59+
if (isBoolean(strictShallowCopy) || strictShallowCopy === "class_only")
60+
this.setUseStrictShallowCopy(strictShallowCopy)
6061
if (isBoolean(config?.useStrictIteration))
6162
this.setUseStrictIteration(config!.useStrictIteration)
6263
}

0 commit comments

Comments
 (0)