Home > Mobile >  [TypeScript]: Typing a class on the `globalThis` variable
[TypeScript]: Typing a class on the `globalThis` variable

Time:11-21

I am trying to add type definitions to variable on globalThis that should act as a class. In JavaScript:

globalThis.X = class {
  ...
}

I am having trouble adding the type definitions on the globalThis object to allow this to work.

declare global {
  module globalThis {
    // Doesn't work. TypeScript error in declaration file.
    var X = (class {
      ...
    })

    // Doesn't work. TypeScript error on usage.
    class X {
      ...
    }
  }
}
const x = new globalThis.X();

console.log(x.value); // This works and will return the actual value on x.

See codesandbox for example reproduction.

CodePudding user response:

In TypeScript, by adding new before the function definition it will act as a constructor. In your example:

declare global {
  module globalThis {
    interface XType {
      value: number;
    }
    var X: new (x?: number, y?: number) => XType;
  }
}

Then when you try to use new globalThis.X(), you should get a type safe variable as the output of type XType.

  • Related