Search code examples
javascripttypescriptnode.js-stream

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


Solution

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