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

avatar
Borislav Hadzhiev

Last updated: Feb 27, 2024
2 min

banner

# 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

# Add DOM to the lib array in your tsconfig.json file

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

tsconfig.json
{ "compilerOptions": { "lib": [ "es2018", "DOM" // ๐Ÿ‘ˆ๏ธ Add this ], }, }
The code for this article is available on GitHub

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.

# Set the target property in tsconfig.json to ES6

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 code for this article is available on GitHub
The target property changes which JS features are down-leveled 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.

# Delete your node_modules and reinstall your dependencies

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

If you are on macOS or Linux, issue the following commands in bash or zsh.

shell
# for macOS and Linux rm -rf node_modules rm -f package-lock.json rm -f yarn.lock # ๐Ÿ‘‡๏ธ clean npm cache npm cache clean --force # ๐Ÿ‘‡๏ธ install packages npm install

If you are on Windows, issue the following commands in CMD.

cmd
# for Windows rd /s /q "node_modules" del package-lock.json del -f yarn.lock # ๐Ÿ‘‡๏ธ clean npm cache npm cache clean --force # ๐Ÿ‘‡๏ธ install packages npm install

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

The code for this article is available on GitHub

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev