Search code examples
javascriptnode.jsangularreactjstypescript

TypeScript: TypeError: App is not a constructor


I just started with typescript and trying to create an instance to the typescript class but I am unsuccessful.

Below are my files

App.ts

import { EventEmitter } from 'events';

interface Emitter extends EventEmitter {

}
class App {
   constructor(protected app: Emitter){}
}

export default = App;

I am generating App.ts to App.js file using tsc command. The file got generated in dist folder as App.js

I have other file called Test.js

In Test.js I am importing generated App.js file and created an instance to it like below but I get below error

TypeError: App is not a constructor

Test.js

const App = require("./dist/App);

module.exports = function(app){
    const appInstance = new App(app)
}

I don't understand why this is throwing such error though I have constructor available in App.ts file.

Am I doing something wrong in App.ts file and that's why I get the above error?

How can I resolve this issue?


Solution

  • Typescript compiles export default = App; as an export of an Object with a property default.

    You can solve that with 2 methods:

    1. Change your require in the js file to that: const App = require("./dist/App).default;
    2. Add to your tsconfig.json file in the compilerOptions allowSyntheticDefaultImports: false.