From 51f381f9f127128f22f88cb318f0eeabaed7dde6 Mon Sep 17 00:00:00 2001 From: nirmal shaji Date: Sat, 5 Sep 2026 14:27:51 +0530 Subject: [PATCH] fix: guard indexed access in applyPatches and shallowCopy for strict TS Under `noUncheckedIndexedAccess`, indexing an array/record yields `T | undefined`, so `patches[i]` in `applyPatches` and `descriptors[key]` in `shallowCopy` are typed as possibly-undefined. Reading their members then fails to compile with TS18048 ("'patch'/'desc' is possibly 'undefined'"), breaking builds that enable this option. Add an early `if (!patch) continue` / `if (!desc) continue` guard right after each indexed read so TypeScript narrows the value for the rest of the loop body. These indices are always in range at runtime, so the guards can never fire and runtime behavior is unchanged. Fixes #1143 --- src/core/immerClass.ts | 1 + src/utils/common.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/core/immerClass.ts b/src/core/immerClass.ts index 2922f6121..240a493be 100644 --- a/src/core/immerClass.ts +++ b/src/core/immerClass.ts @@ -208,6 +208,7 @@ export class Immer implements ProducersFns { let i: number for (i = patches.length - 1; i >= 0; i--) { const patch = patches[i] + if (!patch) continue if (patch.path.length === 0 && patch.op === "replace") { base = patch.value break diff --git a/src/utils/common.ts b/src/utils/common.ts index 513c153e8..d047a1d53 100644 --- a/src/utils/common.ts +++ b/src/utils/common.ts @@ -216,6 +216,7 @@ export function shallowCopy(base: any, strict: StrictMode) { for (let i = 0; i < keys.length; i++) { const key: any = keys[i] const desc = descriptors[key] + if (!desc) continue if (desc[WRITABLE] === false) { desc[WRITABLE] = true desc[CONFIGURABLE] = true