Get Off My Lawn Get Off My Lawn - 3 months ago 21
Javascript Question

Import classes into the global scope

I am trying to import a class into the global scope, and I am able to do it, but then when I try to extend the class I get an error saying:

Type 'any' is not a constructor function type.

So this is what I am doing to get that error:


const MyClass = require('./core/MyClass');

class MyTestClass extends MyClass {


I then tried using
import MyClass from './core/MyClass'
, instead of a const, but that seems as if it is only within the scope of the current file, which doesn't help me either.


export default class MyClass {


I have tried using namespaces which works the way I want in typescript, but once compiled into javascript the namespace is undefined.

Is there a way I can import my class into the global scope and not get the error above when extending the class?


In your code you have :


If you don't have import / export in your file then TypeScript assumes the file is global. However depending upon your usage of the file (e.g in NodeJS or if using a bundler like webpack) the file is still a module and not global.

Cool, with that out of the way you can put something on the global like:

export default class MyClass {
(global as any).MyClass = MyClass;

Be sure to include node.d.ts to get global.


And of course I would also like to warn against default as the const / require you wrote is also wrong. You need something like const {default} = require('module/foo');. More: