5

有什么方法可以处理 typescript 声明文件中的接口或变量,比如类,以便能够从中扩展一个类?

像这样:

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;
   };

}

现在我必须像这样重新定义 EventEmitter 接口并使用我自己的 EventEmitter 声明。

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;
};

稍后在我的 TypeScript 文件中扩展它

import tedious = module('tedious');

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

2 回答 2

2

我不知道回到 2013 年,但现在很容易:

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

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

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

我一直在寻找这个问题的答案,终于弄明白了。

于 2015-08-28T21:13:49.173 回答
1

它应该可以正常工作,例如:

// 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);
   }
}

您放入文件中的任何内容都可以放入 .d.ts 文件中。

试试看

于 2013-05-27T23:26:09.400 回答