Search code examples
javascriptvisual-studio-codejsdoc

How does one declare a variable with the type of global object (of other JavaScript Context)?


How can one declare a variable to have the type of global object (of other JavaScript context); that is, it contains all JavaScript built-in objects, but it is not typeof globalThis (which is automatically resolved for user global variables by vscode)?

globalThis.abc = 123;

// How to declare this type?
// {typeof globalThis} will have property 'abc', which is unwanted.
/** @type {???} */ var otherContextGlobal = <...>;

Thank you.


Solution

  • You can use typeof globalThis but exclude custom properties by using TypeScript utility types in JSDoc. Since JSDoc doesn’t directly support excluding properties, you can work around it by creating a helper type:

    /**
     * @typedef {Omit<typeof globalThis, 'abc'>} OtherContextGlobal
     */
    
    /** @type {OtherContextGlobal} */
    var otherContextGlobal;

    Explanation:

    1. typeof globalThis gives all global built-in objects plus any custom properties like abc.
    2. Omit<typeof globalThis, 'abc'> ensures that abc is excluded from the type.
    3. This way, otherContextGlobal has the same type as a fresh JavaScript global object without custom user-defined properties.