扩展globalThis接口触发‘Declaration name conflicts with built-in global identifier 'globalThis'’错误的原因及与Window接口差异咨询
globalThis like I do with Window? Great question! Let’s break down the key differences between how TypeScript handles globalThis and Window, and why you’re seeing that error:
globalThisis a global value, not an interface
In TypeScript’s type system,globalThisis defined as a concrete value (the actual reference to the global object in your environment). When you try to declareinterface globalThis { whatever: string }, you’re attempting to create an interface with the exact same name as an existing global value. TypeScript blocks this because an identifier can’t represent both a value and an interface in the same scope—this is exactly what the "Declaration name conflicts with built-in global identifier" error is telling you.Windowis an interface built for declaration merging
By contrast,Windowis explicitly defined as an interface in TypeScript’s DOM type definitions. TypeScript has a feature called interface declaration merging that lets you re-declare the same interface multiple times; the compiler automatically combines all properties from each declaration into a single, unified interface. That’s whyinterface Window { whatever: string }works perfectly—you’re just adding a new property to the existingWindowinterface without any name conflicts.
How to properly extend globalThis's type
If you want to add properties to globalThis, you need to extend its underlying type (the capitalized GlobalThis interface) inside a declare global block. Here’s the correct approach:
declare global { interface GlobalThis { whatever: string; } } // Now you can use this property without errors globalThis.whatever = "Hello, global!";
This works across all JavaScript environments (browsers, Node.js, etc.). If you’re only targeting browsers, extending the Window interface will also affect globalThis (since globalThis references window there), but the GlobalThis approach is more universal.
内容的提问来源于stack exchange,提问作者Ollie Williams

