簡體   English   中英

從Typescript中的聲明接口擴展一個類

[英]Extend a class from a declaration interface in 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);
   }
}

我在2013年不知道,但現在很容易:

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

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

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

我一直在尋找答案,最后想出來了。

它應該工作正常,例如:

// 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文件中。

試試吧

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM