typescript: the method Status will be undefined during extends MemoryStream

34 Views Asked by At

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
2

There are 2 best solutions below

0
Ricky Mo On BEST ANSWER

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;
    }
}
0
user-id-14900042 On

I assume memorystream is npm's one.

Yes, you will not inherit members correctly without calling base class' constructor by super().