10
votes

I am using Mocha/Chai to unit test and am mocking window as follows:

global.window = { innerHeight: 1000, innerWidth: 1000 };

Understandably, TSLint is complaining that:

Property 'window' does not exist on type 'Global'

A few questions... is Global a built in NodeJS/Typescript type? I'm currently silencing the warning with declare var global at the top of the file... but is this the best way to handle this? I noticed I can also resolve the warning with:

declare global {
    namespace NodeJS {
        interface  Global {
            window: any;
        }
    }
}

Preferably, I'd like to extend the existing Global type to also accept a window property. Thanks.

1
You can also reference the window object like this in TS: (<any>window). Not pretty IMHO but does suppress the warningA1rPun
I don't see anything wrong with the declaration merging you're doing... maybe I'd suggest making it {window: Window} instead of {window: any}, but that's up to you.jcalz

1 Answers

6
votes

is Global a built-in NodeJS/Typescript type?

Yes. See @types/node/index.d.ts; in that file, they declare a NodeJS namespace, and within that, a Global interface (just as you've done).

I'm currently silencing the warning with declare var global

Sounds like you don't have the Node typings installed (those typings include the line declare var global: NodeJS.Global; so you shouldn't have to make any such declarations yourself). Run:

npm install --save-dev @types/node

or, if you use yarn:

yarn add -D @types/node

Preferably, I'd like to extend the existing Global type to also accept a window property.

You're mostly there. Just replace window: any; with window: Window;. Note: you will need your tsconfig.json's lib section to include dom to provide the Window interface.

You may soon find that you also want to augment Global document and navigator (again, both of these are defined in the dom lib, and hence require it):

interface Global {
    document: Document;
    window: Window;
    navigator: Navigator;
}