简体   繁体   中英

typeof window == “undefined” throws an error while using ts-node

I have some code within which I'm using typeof window == "undefined" to check whether there is a browser environement. When I'm launching this code with ts-node , I'm getting this:

typings/Console.ts:36:10 - error TS2304: Cannot find name 'window'.

36      typeof window == "undefined"
               ~~~~~~

AFAIK typeof is kind of operator that is safe to use with not defined variables, and it works well both in browser and in NodeJS environement. But as far as I start to use it with ts-node , it starts to throw.

My tsconfig.json

{
    "compilerOptions": {
        "module": "CommonJS",
        "target": "es5",
        "moduleResolution": "node",
        "baseUrl": "src",
        "allowSyntheticDefaultImports": true,
        "noImplicitAny": true,
        "strict": false,
        "sourceMap": true,
        "traceResolution": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "strictNullChecks": true,

        "allowJs": false,
        "declaration": false,
        "removeComments": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true,
        "types": [ "node" ],
        "lib": [ "es6" ],
        "downlevelIteration": true,
        "resolveJsonModule": true,
        "typeRoots": [
            "../node_modules/@types"
        ]
    }
}

So, what the trick? Thanks in advance!

try add to lib in tsconfig "DOM"

For me it worked to first declare the variable to TypeScript, so:

declare var window;

if(typeof window == "undefined"){
// code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM