打字稿无法找到名称窗口或文档

无论哪种情况:

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

我得到 error TS2304: Cannot find name 'window'.

对于应该安装的定义文件,我是否在 tsconfig.json中遗漏了什么?

我得到的消息时,运行 tsc和在 vscode

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"
]
}

我的回答: 与 tsconfig.json一起使用时,我的目标是 es5并使用 lib: ["es2015", "dom"]

72923 次浏览

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.

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/**/*"]
}

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