简体   繁体   English

从Typescript中的声明接口扩展一个类

[英]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. 现在我必须像这样重新定义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;
};

And extend it later inside my TypeScript File 稍后在我的TypeScript文件中扩展它

import tedious = module('tedious');

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

I dunno about back in 2013, but now it's easy enough: 我在2013年不知道,但现在很容易:

/// <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. 我一直在寻找答案,最后想出来了。

It should work fine eg: 它应该工作正常,例如:

// 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. 您放入文件中的任何内容都可以放入.d.ts文件中。

Try it 试试吧

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM