Skip to content

Commit b00474e

Browse files
fix: remove global var Iterator declaration conflicting with ESNext lib (#1290)
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
1 parent 6c7a3de commit b00474e

1 file changed

Lines changed: 12 additions & 10 deletions

File tree

src/plugins/mapset.ts

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,16 @@ import {
2020
handleCrossReference
2121
} from "../internal"
2222

23-
declare global {
24-
// `Iterator.from` was added in ES2025.
25-
var Iterator:
26-
| undefined
27-
| {
28-
from<T, TReturn>(iterable: Iterator<T, TReturn>): IterableIterator<T>
29-
}
30-
}
23+
// Feature-detect `Iterator.from` (added in ES2025) without augmenting the
24+
// global scope. Declaring `var Iterator` in a `declare global` block leaks a
25+
// conflicting global variable into the bundled `.d.ts` (TS2403 when compiled
26+
// against the ESNext lib). We cast via `globalThis` to satisfy the type checker
27+
// while keeping the runtime feature detect accurate. (#1273)
28+
const _globalIterator = (globalThis as any).Iterator as
29+
| undefined
30+
| { from: <T>(iterable: Iterator<T>) => IterableIterator<T> }
31+
const hasIteratorFrom =
32+
typeof _globalIterator?.from === "function"
3133

3234
export function enableMapSet() {
3335
class DraftMap extends Map {
@@ -173,8 +175,8 @@ export function enableMapSet() {
173175
function iteratorFrom<T, TReturn>(
174176
iterable: Iterator<T, TReturn>
175177
): IterableIterator<T> {
176-
if (typeof Iterator !== "undefined") {
177-
return Iterator.from(iterable)
178+
if (hasIteratorFrom) {
179+
return _globalIterator!.from(iterable)
178180
}
179181

180182
const iterator: IterableIterator<T> = {

0 commit comments

Comments
 (0)