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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Great answer. Maybe add a note on why using any is wrong in this case and bad in general?
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 stackoverflow.com/questions/18378503/…
@xhallix Yes, you can. I've just updated the answer for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.