【问题标题】:Typescript on node.js stream - incorrectly extends base class 'Transform'node.js 流上的打字稿 - 错误地扩展了基类“Transform”
【发布时间】:2017-11-25 10:09:07
【问题描述】:
import { Transform } from "stream";    
export class TestStream extends Transform {

        constructor(options) {
            super(options);
        }

        write(data: any, enc: string, cb: Function) {
            return super.write(data, enc, cb);
        }
    }

上面的代码出现以下错误。

类“TestStream”错误地扩展了基类“Transform”。 属性“写入”的类型不兼容。 类型 '(data: any, enc: string, cb: Function) => boolean' 不可分配给类型 '{ (chunk: any, cb?: Function): boolean; (chunk: any, encoding?: string, cb?: Function): boolean; }'。

【问题讨论】:

    标签: javascript typescript node.js-stream


    【解决方案1】:

    由于write 支持以下重载:

    write(chunk: any, cb?: Function): boolean;
    write(chunk: any, encoding?: string, cb?: Function): boolean;
    

    第二个参数可以是编码或回调。你必须在你的代码中处理它:

    write(chunk: any, encodingOrCB?: string | Function, cb?: Function): boolean {
        if (typeof encodingOrCB == "string") {
            return super.write(chunk, encodingOrCB, cb);
        }
        else {
            return super.write(chunk, encodingOrCB);
        }        
    }
    

    【讨论】:

      【解决方案2】:

      您错误地覆盖了函数write

      试试

      write(data: any, enc?: string, cb?: Function) {
          return super.write(data, enc, cb);
      }
      

      注意?它用于可选参数

      【讨论】:

      • 现在我在错误消息中收到额外的Types of parameters 'enc' and 'cb' are incompatible. Type 'Function' is not assignable to type 'string'.
      猜你喜欢
      • 1970-01-01
      • 2017-04-27
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 2017-12-01
      • 1970-01-01
      相关资源
      最近更新 更多