Cannot find name 'window' or 'document' in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 19, 2022

banner

Photo from Unsplash

Cannot find name 'window' or 'document' in TypeScript #

To solve the "Cannot find name window or document" error, add dom to the lib array in your tsconfig.json file. The dom definitions include both window and document. Adding the dom type definitions is required for programs running in the browser.

cannot find name window document

Open your tsconfig.json file and make sure to add DOM to your lib array.

tsconfig.json
{ "compilerOptions": { "lib": [ "es2018", "dom" // 👈️ Add this ], }, }

Once you have added dom to your lib array in tsconfig.json the error should be resolved.

The lib setting tells TypeScript which type definitions it should include.

If your code runs in the browser, add the dom string to your lib array to be able to use the window and document global variables in your TypeScript code.

If that doesn't work, make sure the target property in your tsconfig.json file is set to something recent - ES6 is a good choice.

tsconfig.json
{ "compilerOptions": { "target": "es6" } }
The target setting changes which JS features are downleveled and which are left intact. For example, arrow functions get converted to regular functions if your target is ES5 or lower.

Modern browsers support all ES6 features, so try setting your target to es6 or a more recent version.

If the error is not resolved, try to delete your npm_modules and package-lock.json, re-run npm install and reload your IDE.

shell
rm -rf node_modules package-lock.json npm install

Make sure to restart your IDE if the error persists. VSCode glitches often and a reboot solves things sometimes.

Conclusion #

To solve the "Cannot find name window or document" error, add dom to the lib array in your tsconfig.json file. The dom definitions include both window and document. Adding the dom type definitions is required for programs running in the browser.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.