Typescript cannot find name window or document
Asked Answered
C

6

125

For either case:

document.getElementById('body');
// or
window.document.getElementById('body');

I get error TS2304: Cannot find name 'window'.

Am I missing something in tsconfig.json for a definition file I should install?

I get the message when running tsc and in vscode

tsconfig.json:

{
    "compilerOptions": {
        "allowJs": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "jsx": "react",
        "module": "commonjs",
        "moduleResolution": "node",
        "noEmitOnError": true,
        "noImplicitAny": false,
        "sourceMap": true,
        "suppressImplicitAnyIndexErrors": true,
        "target": "ES2016",
        "typeRoots": [
            "node_modules/@types/",
            "typings/index.d.ts"
        ]
    },
    "exclude": [
        "node_modules",
        "**/*-aot.ts"
    ]
}

My Answer: For use with tsconfig.json I target es5 and use lib: ["es2015", "dom"]

Crinose answered 26/12, 2016 at 21:9 Comment(2)
Where do you get that error? In your IDE, or when running tsc? What is your current tsconfig.json file? You need to provide more relevant information if you want helpPiddling
@NitzanTomer I added the information you requested.Crinose
P
108

It seems that the problem is caused by targeting ES2016.
Are you targeting that for a reason? If you target es6 the error will probably go away.

Another option is to specify the libraries for the compiler to use:

tsc -t ES2016 --lib "ES2016","DOM" ./your_file.ts

Which should also make the error go away.

I'm not sure why the libs aren't used by default, in the docs for compiler options it states for the --lib option:

Note: If --lib is not specified a default library is injected. The default library injected is:
► For --target ES5: DOM,ES5,ScriptHost
► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

But it doesn't state what are the default libraries when targeting ES2016.
It might be a bug, try to open an issue, if you do please share the link here.

Piddling answered 26/12, 2016 at 22:43 Comment(10)
Targeting ES6 did the trick! I originally targeted ES2016 because I plan to put the resulting javascript through webpack so I didn't think it would make much difference.Crinose
It makes sense to me that --libs would have to be explicitly declared instead of some arbitrary defaults.Isentropic
I'm getting the same issue at code time in VSCode with an Angular 2 project built with Angular CLI, and switching to "es6" in both/either tsconfig.json and tsconfig.app.json didn't resolve it; neither did adding "dom" to tsconfig.json (it's already in tsconfig.app.json). There are no compile-time or runtime errors, but the red squiggly is annoying while coding.Plotter
@S.Greylyn If there are no compile errors then it's an issue with your VSCode. I've never used it.Piddling
@S.Greylyn use "lib": ["dom"] in tsconfig.json. That worked for me.Liquesce
Baffled what target actually does, is it just for typedefs? And lib... is also for typedefs?Faustena
@DominicTobias target specifies to which version of js the output of the compilation. For example, if you want your code to run on older browsers, you don't want es6 feature (and above). The lib option has default values based on the target. You can override the defaults if you're sure that the environment at runtime does include the features.Piddling
Also of note: If you already have lib in your tsconfig.json, it might help to remove it again. lib will be autofilled with what makes sense for your target but if you have already defined lib, it will be left as-is, meaning you might miss some libs.Dermatophyte
@S.G. I have now the same issue after accidentely ctrl-clicked on window in code at VSCode Editor. I also have dom in tscofig lib setting. Did you solved the issue?Istria
@Istria I believe I either found some VSCode setting that disabled linting for that particular error, or I just ignored it until that project was done, but I cannot rightly remember. Good luck.Plotter
M
165

use

"lib": ["dom"]

in tsconfig.json

e.g.

{
  "compilerOptions": {
    "lib": ["es5", "es6", "dom"],
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es6",
    "moduleResolution": "node",
    "jsx": "react"
  },
  "include": ["./src/**/*"]
}
Mohsen answered 5/3, 2018 at 14:14 Comment(5)
FWIW this is what solved it for me. Should be the accepted answer, because in some situations (starter kits or tools that already take care of running tsc for you, you're not so easily able to change the CLI args passed to it, but you almost surely control tsconfig.json)Germano
i have added this to my lib but its not still working. "lib": [ "es5", "es6", "dom", "dom.iterable", "esnext" ],Jedidiah
Same @AdharshM...I wonder is there a recent issue?Rhyme
I'm also encountering an issue, my code was working fine and then it wasn't, but I hadn't changed anything TS-related and was already using dom. I'll try use an older version of TS, I updated yesterday (but didn't notice this issue since)Lectern
@AdharshM This is likely due to github.com/lquixada/cross-fetch/issues/104, at least that was the case for me.Lectern
P
108

It seems that the problem is caused by targeting ES2016.
Are you targeting that for a reason? If you target es6 the error will probably go away.

Another option is to specify the libraries for the compiler to use:

tsc -t ES2016 --lib "ES2016","DOM" ./your_file.ts

Which should also make the error go away.

I'm not sure why the libs aren't used by default, in the docs for compiler options it states for the --lib option:

Note: If --lib is not specified a default library is injected. The default library injected is:
► For --target ES5: DOM,ES5,ScriptHost
► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

But it doesn't state what are the default libraries when targeting ES2016.
It might be a bug, try to open an issue, if you do please share the link here.

Piddling answered 26/12, 2016 at 22:43 Comment(10)
Targeting ES6 did the trick! I originally targeted ES2016 because I plan to put the resulting javascript through webpack so I didn't think it would make much difference.Crinose
It makes sense to me that --libs would have to be explicitly declared instead of some arbitrary defaults.Isentropic
I'm getting the same issue at code time in VSCode with an Angular 2 project built with Angular CLI, and switching to "es6" in both/either tsconfig.json and tsconfig.app.json didn't resolve it; neither did adding "dom" to tsconfig.json (it's already in tsconfig.app.json). There are no compile-time or runtime errors, but the red squiggly is annoying while coding.Plotter
@S.Greylyn If there are no compile errors then it's an issue with your VSCode. I've never used it.Piddling
@S.Greylyn use "lib": ["dom"] in tsconfig.json. That worked for me.Liquesce
Baffled what target actually does, is it just for typedefs? And lib... is also for typedefs?Faustena
@DominicTobias target specifies to which version of js the output of the compilation. For example, if you want your code to run on older browsers, you don't want es6 feature (and above). The lib option has default values based on the target. You can override the defaults if you're sure that the environment at runtime does include the features.Piddling
Also of note: If you already have lib in your tsconfig.json, it might help to remove it again. lib will be autofilled with what makes sense for your target but if you have already defined lib, it will be left as-is, meaning you might miss some libs.Dermatophyte
@S.G. I have now the same issue after accidentely ctrl-clicked on window in code at VSCode Editor. I also have dom in tscofig lib setting. Did you solved the issue?Istria
@Istria I believe I either found some VSCode setting that disabled linting for that particular error, or I just ignored it until that project was done, but I cannot rightly remember. Good luck.Plotter
N
29

If you are using bun instead of node, then you need to use bun add @types/web -D.

The problem is explained at https://github.com/oven-sh/bun/issues/3030

Solution

https://github.com/oven-sh/bun/issues/463#issuecomment-1636727109

Note: Adding the types reference to your tsconfig.json, as explaining on the GitHub issue, looks not to be mandatory. Only installing the dependency looks enough to get rid of the error.

Nagging answered 14/9, 2023 at 8:39 Comment(2)
Thanks. This is the solution for bun for the moment.Tapley
Same here. i added to one of the monorepo packages the bun and it broke the types for all of the other packages. doing this resolve it.Cogan
T
13

Update: To avoid having to add these references to every file, see stackoverflow.com/a/77103144

I was using bun, and adding the following triple-slash directives at the top of the relevant TypeScript file solved it:

/// <reference lib="dom" />
/// <reference lib="dom.iterable" />

This is because setting "types": ["bun-types"] means TypeScript will ignore other global type definitions, including lib: ["dom"].

The same applies to other global type definition libs like webworker.

See how to add DOM types in bun's documentation for up-to-date information.

Tennies answered 13/3, 2023 at 19:16 Comment(2)
Bun's documentation mentions how to add DOM types without removing bun-types from your tsconfig.json types.Ric
@NielThiart Thanks, i updated the answer to reflect the docs. Even though I haven't tested the solution, this fix sounds like it is a lot better.Tennies
E
5

For me, running this command fixed my issue.

npm add -d @types/web
Ermeena answered 4/10, 2023 at 9:57 Comment(1)
same for me. Already had lib: ["dom"] was missing "types": ["web"]Carcassonne
T
1

What fixed it for me was changing tsconfig.json's "target" to "es6". It was "es2015" before.

Tesler answered 22/2, 2022 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.