Description
Window in a web page serves a dual purpose. it implements the Window
interface representing the web page main view, but also acts as an alias to the global namespace. All global variables are accessible on the window
object at run-time; this applies to builtin JS declarations like Array
, Math
, JSON
, Intl
as well as global DOM declarations like HTMLElement
, Event
, HTMLCollection
, etc...
TypeScript today does not model this behavior. For instance window.Math
is not defined, so is all the HTMLElement
family of declarations.
Most of the patterns window
is used to access global declarations are anti-patterns (see a good article about window usage), the main exception is testing for API existence, e.g.: if (window.MutationObserver) { ... }
. There is not really a legal way to do this out-of-the-box in TS today.
Our recommendation has been to manually add a declaration for the global object on Window
, e.g.:
declare global {
interface Window {
MutationObserver?: typeof MutationObserver;
}
}
This is a. inconvenient and b. not easy to find if you are new to TS. Here is a list of issues we have so far related to this issue:
- Blob property is missing on Window interface #8866
window.Blob
- ImageBitmap interface missing #14402
window.createImageBitmap
- Property Math is missing on Window interface #9325
window.Math
- URL is missing from Window interface #3753
window.URL
- MutationObserver API declarations missing #11305
window.MutationObserver
- window.PointerEvent is undefined #18756
window.PointerEvent
- Event types do not exist in the Window interface #19758
window.MouseEvent
- window.Element is a stable API, but is not included in the interface Window(lib.d.ts:19060). #23886
window.Element
- Add typings for PerformanceObserver #25651
window.PerformanceObserver
It is also worth noting that the same problem occurs with self
in web workers and global
for node
Possible options here:
- support a global type (tracked by Access
global
as a type #14052), and allowWindow
to extend from it. - generate lib.d.ts with all global declarations mirrored on
Window
.