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
mand. 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?
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
mand. 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.
Share Improve this question edited Oct 25, 2018 at 15:35 Hemadri Dasari asked Oct 25, 2018 at 15:18 Hemadri DasariHemadri Dasari 34k40 gold badges124 silver badges165 bronze badges 2Am I doing something wrong in App.ts file and that's why I get the above error?
How can I resolve this issue?
-
Shouldn't the interface and the class be declared with different names? They are both called
App
. You can try declaring the interface asIApp
. – Martin Parenteau Commented Oct 25, 2018 at 15:33 - @ConnorsFan Sorry my bad it was typo error. I updated my question – Hemadri Dasari Commented Oct 25, 2018 at 15:35
3 Answers
Reset to default 7Typescript piles export default = App;
as an export of an Object with a property default.
You can solve that with 2 methods:
- Change your require in the js file to that:
const App = require("./dist/App).default;
- Add to your
tsconfig.json
file in the pilerOptionsallowSyntheticDefaultImports: false
.
you have exported App by wrong way, export it like so
export default class App {
constructor(protected app: App){}
}
In my case it was because the file had the same name as the class.
Ie. class MyThing {}
was defined in a file called MyThing.ts
.
Renaming the file to mything.ts
solved the problem.
Hope this helps someone.