Search code examples
typescriptextends

typescript: the method Status will be undefined during extends MemoryStream


If I remove the extends MemoryStream below, then everything works as expected - the status method can be called. But if I use extends MemoryStream, then the status method becomes undefined.

What am I doing wrong?

import MemoryStream from 'memorystream';

export interface ResponseInterface extends NodeJS.WritableStream{
    status(s: number): ResponseInterface
}

export class FakeResponce extends MemoryStream implements ResponseInterface {
    status(s: number): ResponseInterface{
        console.log("status work!") 
        return this;
    }
}

const a : ResponseInterface = new FakeResponce();
console.log(`status is ${a.status}`);  // status is undefined
a.status(); // ERROR

Updated:

I fixed it. But is this really the best way?

import MemoryStream from 'memorystream';

export interface ResponseInterface extends NodeJS.WritableStream{
    status(s: number): ResponseInterface
}

export class FakeResponce extends MemoryStream implements ResponseInterface {
    constructor(){
        super()
        this.status = (s: number): ResponseInterface => {
            console.log("status work!") 
            return this;
        }
    }
    status: (s: number) => ResponseInterface
}

const a : ResponseInterface = new FakeResponce();
console.log(`status is ${a.status}`);
a.status(); // Ok

Solution

  • memorystream uses util.inherits from nodejs, which is not compatible with ES6 extends, see https://github.com/nodejs/node/issues/4179

    A workaround would be changing it to a property instead of a method, which is what your fix does. But the implementation can be inline with the declaration instead of separating to within the constructor.

    export class FakeResponce extends MemoryStream implements ResponseInterface {
    
        status : (s: number) => ResponseInterface = (s) => {
            console.log("status work!")
            return this;
        }
    }