TypeScript: declare constructor on global window

Viewed 440

I am trying to declare an expected constructor on the window object.

declare global {
  interface Window {
    MyApi: {
      MyClassType: any
    }
  }
}

expect(new window.MyApi.MyClassType()).toNotBe(undefined)

What should any be?

3 Answers

It should be the type of your class, e.g.

class MyClass {
  constructor(public name: string) {}
}

declare global {
  interface Window {
    MyApi: {
      MyClassType: MyClass;
    };
  }
}

A nice thing about typescript is that you can use class as types

So in your case make your class

class MyClass {}

And in declaration

MyClassType: MyClass

It looks like you want window.MyApi.MyClassType to be your class/constructor and not an instance. If you wanted it to be an instance, then you could use MyClassType as the type. Otherwise you need typeof MyClassType.

But to get it working right, if you want to use the declare global syntax you need to make sure that the file where that is declared needs to contain at least one import or export otherwise you'll get an error "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."

Here's a working example:

class MyClassType {
    // Your class implementation
}
export default MyClassType;

window.MyApi = {
  MyClassType: MyClassType,
};

declare global {
  interface Window {
    MyApi: {
      MyClassType: typeof MyClassType;
    };
  }
}

But this is also another possibility in case you don't want the file to have any imports or exports:

class MyClassType {
    // Your class implementation
}

declare var MyApi: { // eslint-disable-line
  MyClassType: typeof MyClassType;
};

window.MyApi = {
  MyClassType: MyClassType,
};

These let you access the API like so:

import './my-api';
const foo = new window.MyApi.MyClassType();
Related