首页 文章

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

提问于
浏览
0

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

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)=> 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 回答

  • 1

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

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

    使用

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

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

相关问题