Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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", ...]
...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading