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

Viewed 2230

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!

2 Answers

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

declare var window;

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