如何在typescript

时间:2017-08-19 06:03:11

标签: node.js typescript

我已经创建了一个从Node.js流库类扩展的类,在这个类中做了一些特殊的事情。

import * as stream from 'stream';

export class PipeWritable extends stream.Writable {

   ...

   public end(): void;
   public end(chunk: any, cb?: Function): void;
   public end(chunk: any, encoding?: string, cb?: Function): void {
      super.end();
   }

}

这会导致错误:
error TS2394: Overload signature is not compatible with function implementation

重载方法的参数结构从@types/node/index.d.ts以1:1复制。

我知道typescript不支持方法重载,但如果你声明模块,你可以做类似的事情,正如你在Node.js模块流中看到的那样:

declare module "stream" {
    export class Writable extends Stream implements NodeJS.WritableStream {
        ...
        end(): void;
        end(chunk: any, cb?: Function): void;
        end(chunk: any, encoding?: string, cb?: Function): void;
        ...
    }
}

所以我的问题是,如何覆盖stream.Writable方法end()

1 个答案:

答案 0 :(得分:2)

在您的代码段中,这些是过载签名:

public end(): void;
public end(chunk: any, cb?: Function): void;

这是实施签名:

public end(chunk: any, encoding?: string, cb?: Function): void {
  super.end();
}

实现签名与过载签名不兼容。

第一个重载不兼容,因为它没有参数,并且实现签名具有非可选的chunk参数。

第二个重载不兼容,因为它的第二个参数是可选的Function,并且与可选的string不兼容。

您必须提供具有与所有重载兼容的签名的实现。例如:

// The overload signatures:

public end(): void;
public end(chunk: any, cb?: Function): void;
public end(chunk: any, encoding?: string, cb?: Function): void;

// The implementation:

public end(...args: any[]): void {
  super.end(...args);
}

请注意,当函数具有过载签名时,TypeScript仅匹配具有过载签名的函数调用;实施签名考虑。