简体   繁体   中英

Typescript on node.js stream - incorrectly extends base class '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);
        }
    }

I'm getting following error on the above code.

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; }'.

Since write supports the following overloads:

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

The second parameter could be either encoding or callback. You have to handle it in your code:

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

you are overriding the function write incorrectly.

try

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

Notice ? it is used for optional parameters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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