Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

javascript - Typescript cannot find name window or document

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...