node.js流上的Typescript - 错误地扩展基类'Transform'

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

我在上面的代码中遇到以下错误 .

Class 'TestStream' incorrectly extends base class 'Transform'. Types of property 'write' are incompatible. Type '(data: any, enc: string, cb: Function) => boolean' is not assignable to type '{ (chunk: any, cb?: Function): boolean; (chunk: any, encoding?: string, cb?: Function): boolean; }'.

回答(2)

3 years ago

由于 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);
    }        
}

3 years ago

你错误地覆盖了函数 write .

尝试

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

注意 ? 它用于可选参数