Skip to content
Myr

fix: remove global `var Iterator` declaration conflicting with ESNext lib (#1290)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

The `declare global { var Iterator }` shim (added to feature-detect ES2025's `Iterator.from`) leaks a global variable declaration into the bundled `dist/immer.d.ts`. When a consumer compiles against the `esnext` lib, tsc reports: error TS2403: Subsequent variable declarations must have the same type. Variable 'Iterator' must be of type 'IteratorConstructor', but here has type '{ from<T, TReturn>(iterable: Iterator<T, TReturn>): IterableIterator<T> } | undefined'. Replace the global augmentation with a module-scoped feature detect that reads the iterator constructor off `globalThis`. The runtime behavior is unchanged (uses `Iterator.from` when available, falls back to the manual iterator), but the emitted `.d.ts` no longer declares a global that clashes with the standard library. Fixes #1273

authored by Erfan · committed by GitHub · parent 6c7a3de · Browse files · 1 file+12 added−10 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+12 added−10 removed

  • other:+12 added−10 removed

1 file+12 added−10 removed

modified:src/plugins/mapset.ts+12 added-10 removed
18 unmodified lines
19 PluginMapSet,20 handleCrossReference21} from "../internal"2223declare global {24 // `Iterator.from` was added in ES2025.25 var Iterator:26 | undefined27 | {28 from<T, TReturn>(iterable: Iterator<T, TReturn>): IterableIterator<T>29 }30}23// Feature-detect `Iterator.from` (added in ES2025) without augmenting the24// global scope. Declaring `var Iterator` in a `declare global` block leaks a25// conflicting global variable into the bundled `.d.ts` (TS2403 when compiled26// against the ESNext lib). We cast via `globalThis` to satisfy the type checker27// while keeping the runtime feature detect accurate. (#1273)28const _globalIterator = (globalThis as any).Iterator as29 | undefined30 | { from: <T>(iterable: Iterator<T>) => IterableIterator<T> }31const hasIteratorFrom =32 typeof _globalIterator?.from === "function"3334export function enableMapSet() {35 class DraftMap extends Map {36 [DRAFT_STATE]: MapState
137 unmodified lines
174175 function iteratorFrom<T, TReturn>(176 iterable: Iterator<T, TReturn>177 ): IterableIterator<T> {176 if (typeof Iterator !== "undefined") {177 return Iterator.from(iterable)178 if (hasIteratorFrom) {179 return _globalIterator!.from(iterable)180 }181182 const iterator: IterableIterator<T> = {183 ...iterable,
173 unmodified lines