如何修复此类型X不能分配给打字稿中的类型Y错误?

时间:2017-10-10 12:22:58

标签: typescript express

在我的快递应用程序中,我有以下中间件:

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

返回以下打字稿错误:

  

错误TS2322:输入'(chunk:any,encoding:any)=>任何'不是   可分配给'{():void; (buffer:Buffer,cb?:Function):void;   (str:string,cb?:Function):void; (str:stri ......'。

@types/node/index.d.ts end方法中的

描述如下:

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;

修复此错误的正确类型是什么?

1 个答案:

答案 0 :(得分:1)

从我所看到的,您打算使用其中一个可用的重载:end(data?: any, encoding?: string): void; 如果是这种情况,您只需要使您的功能签名明确兼容。而不是

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

使用

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

并确保正确处理角落情况,例如:根本没有传递参数。