0
votes

In my express app I have the following middleware:

app.use(function(req, res, next) {
  let _end = res.end;
  res.end = function end(chunk, encoding) {
    ...
    return _end.call(res, chunk, encoding);
  };
  next();
});

This return the following typescript error:

error TS2322: Type '(chunk: any, encoding: any) => any' is not assignable to type '{ (): void; (buffer: Buffer, cb?: Function): void; (str: string, cb?: Function): void; (str: stri...'.

in @types/node/index.d.ts end method is described like this:

end(): void;
end(buffer: Buffer, cb?: Function): void;
end(str: string, cb?: Function): void;
end(str: string, encoding?: string, cb?: Function): void;
end(data?: any, encoding?: string): void;

What would be the correct type to fix this error?

1

1 Answers

2
votes

From what I can see, you intend to use one of the available overloads: end(data?: any, encoding?: string): void; If that is the case, you just need to make your function signature explicitly compatible. Instead of

// ...
res.end = function end(chunk, encoding) {
// ...

use

// ...
res.end = function end(chunk?:any, encoding?:string) {
// ...

And make sure that you correctly handle corner cases, e.g. where arguments are not passed at all.