2

Was playing around with Ts and got stuck at this

"use strict";

declare const require: any;

const EventEmitter : any = require('events').EventEmitter;

class Foo extends EventEmitter{ //*error* Type 'any' is not a constructor function type.

    constructor() {
        super();
    }
}

I also tried to assign EventEmitter to an interface type of mine, which gave the same error.

How can I extend a class, with commonjs modules using Typescript?

Thank you

xhallix
  • 2,919
  • 5
  • 37
  • 55

1 Answers1

3

try

"use strict";

import { EventEmitter } from 'events';

class Foo extends EventEmitter {
    constructor() {
        super();
    }
}

You may need to install type definition for 'events' module:

npm install --save @types/node


Update

You can still do the same with require:

"use strict";

import events = require('events');
const EventEmitter = events.EventEmitter;

class Foo extends EventEmitter {
    constructor() {
        super();
    }
}

You should avoid using : any in general so you can use features like IntelliSense and compile-time type checking

Hoang Hiep
  • 2,242
  • 5
  • 13
  • 17
  • 1
    Great answer. Maybe add a note on why using any is wrong in this case and bad in general? – Aluan Haddad Feb 24 '17 at 07:56
  • thanks a lot! I really like the approach, but just for completion, would the `require` solution also be possible using something like `node.d.ts` , like mentioned here http://stackoverflow.com/questions/18378503/importing-node-modules-with-typescript – xhallix Feb 24 '17 at 07:58
  • @xhallix Yes, you can. I've just updated the answer for that. – Hoang Hiep Feb 24 '17 at 08:11