Skip to content

Expose global declarations on window #19816

Closed
microsoft/TypeScript-DOM-lib-generator
#715
@mhegazy

Description

@mhegazy

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:

It is also worth noting that the same problem occurs with self in web workers and global for node

Possible options here:

  1. support a global type (tracked by Access global as a type #14052), and allow Window to extend from it.
  2. generate lib.d.ts with all global declarations mirrored on Window.

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions