Search code examples
javascripttypescripttypesglobal-variablestypescript-typings

How to declare a global variable in TypeScript?


A site that I'm testing using Playwright has a certain non-standard object (say, MY_OBJECT) available on the window. I'm calling this object using page.evaluate, like so:

page.evaluate(
  () => MY_OBJECT.someMethod()
)

Of course, my Playwright project doesn't know anything about MY_OBJECT, so I'm getting an error.

How do I correctly declare MY_OBJECT, so that it is available in the global scope without additional imports, etc.?

I tried creating index.d.ts and adding the following:

declare global {
  var MY_OBJECT: {
    someMethod: () => void;
  };
}

or

declare var MY_OBJECT: {
  someMethod: () => void;
};

but neither does work. I'm still getting TS2304: Cannot find name 'MY_OBJECT'.


Solution

  • Try adding an export statement to your index.d.ts file.

    export {};
    
    declare global {
      var MY_OBJECT: {
        someMethod: () => void;
      };
    }
    

    And make sure the "include" property in your tsconfig.json contains a glob pattern that matches index.d.ts

    {
    "include": ["**/*.ts", ...]
    ...
    }