AmunRa
AmunRa

Reputation: 35

Typescript: Overloading event handlers

I am trying to extend an existing interface to add additional event handlers. The interface I am extending already has several event handlers defined.

Here is the base interface:

export interface Emitter {

  on(event: 'connect', listener: (err: Error) => void ):this;

  on(event: 'end', listener: () => void ):this;
}

Here is also the base class:

export class Emitter extends events.EventEmitter {}

Here is my interface:

export interface EmitterExtended extends Emitter {
  on(event: 'status', listener: (status: ConnectionStatus) => void ):this;
  status?: ConnectionStatus;
}

And here is the error typescript gives:

Interface 'EmitterExtended' incorrectly extends interface 'Emitter'.
Types of property 'on' are incompatible.

Upvotes: 1

Views: 359

Answers (1)

AmunRa
AmunRa

Reputation: 35

Found the solution here

By declaring a module with the same name as the imported module, you can augment existing declarations

import { Observable } from "./observable";
declare module "./observable" {
    interface Observable<T> {
        map<U>(f: (x: T) => U): Observable<U>;
    }
}

Observable.prototype.map = function (f) {
    // ... another exercise for the reader
}

Upvotes: 1

Related Questions