discipulus
discipulus

Reputation: 331

Extend a class from a declaration interface in Typescript

Is there any way to treat an interface or a variable inside a typescript declaration file like class to be able to extend a class from it?

Like this:

declare module "tedious" {

   import events = module('events');

   export class Request extends event.EventEmitter {
       constructor (sql: string, callback: Function);
       addParameter(name: string, type: any, value: string):any;
       addOutputParameter(name: string, type: any): any;
       sql:string;
       callback: Function;
   };

}

Right now i have to redefine the EventEmitter interface like this and use my own EventEmitter declaration.

import events = module('events');

class EventEmitter implements events.NodeEventEmitter{
    addListener(event: string, listener: Function);
    on(event: string, listener: Function): any;
    once(event: string, listener: Function): void;
    removeListener(event: string, listener: Function): void;
    removeAllListener(event: string): void;
    setMaxListeners(n: number): void;
    listeners(event: string): { Function; }[];
    emit(event: string, arg1?: any, arg2?: any): void;
}

export class Request extends EventEmitter {
    constructor (sql: string, callback: Function);
    addParameter(name: string, type: any, value: string):any;
    addOutputParameter(name: string, type: any): any;
    sql:string;
    callback: Function;
};

And extend it later inside my TypeScript File

import tedious = module('tedious');

class Request extends tedious.Request {
   private _myVar:string; 
   constructor(sql: string, callback: Function){
       super(sql, callback);
   }
}

Upvotes: 5

Views: 6928

Answers (2)

Garrett Serack
Garrett Serack

Reputation: 953

I dunno about back in 2013, but now it's easy enough:

/// <reference path="../typings/node/node.d.ts" />
import * as events from "events";

class foo extends events.EventEmitter  {
   constructor() {
      super();
   }

   someFunc() { 
      this.emit('doorbell');
   }
}

I was looking for the answer to this, and finally figured it out.

Upvotes: 2

basarat
basarat

Reputation: 276105

It should work fine e.g.:

// Code in a abc.d.ts 
declare module "tedious" {
   export class Request  {
       constructor (sql: string, callback: Function);
       addParameter(name: string, type: any, value: string):any;
       addOutputParameter(name: string, type: any): any;
       sql:string;
       callback: Function;
   };
}

// Your code: 
///<reference path='abc.d.ts'/>
import tedious = module('tedious');

class Request extends tedious.Request {
   private _myVar:string; 
   constructor(sql: string, callback: Function){
       super(sql, callback);
   }
}

Anything you put in your file you can put in a .d.ts file.

Try it

Upvotes: 1

Related Questions