如何修复typescript中X类型不可分配给Y类型的错误?
在我的express应用程序中,我有以下中间件:如何修复typescript中X类型不可分配给Y类型的错误?,typescript,express,Typescript,Express,在我的express应用程序中,我有以下中间件: app.use(function(req, res, next) { let _end = res.end; res.end = function end(chunk, encoding) { ... return _end.call(res, chunk, encoding); }; next(); }); 这将返回以下typescript错误: 错误TS2322:Type'(块:任意,编码:任意)=>any'
app.use(function(req, res, next) {
let _end = res.end;
res.end = function end(chunk, encoding) {
...
return _end.call(res, chunk, encoding);
};
next();
});
这将返回以下typescript错误:
错误TS2322:Type'(块:任意,编码:任意)=>any'不正确
可赋值给类型“{():void;(buffer:buffer,cb?:Function):void;
(str:string,cb?:函数):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;
修复此错误的正确类型是什么?据我所见,您打算使用一个可用的重载:
end(data?:any,encoding?:string):void;
如果是这种情况,您只需要使函数签名显式兼容
// ...
res.end = function end(chunk, encoding) {
// ...
使用
并确保正确处理角点情况,例如根本不传递参数。从我看到的情况来看,您打算使用一个可用的重载:
end(data?:any,encoding?:string):void;
如果是这种情况,您只需要使函数签名显式兼容
// ...
res.end = function end(chunk, encoding) {
// ...
使用
并确保您正确地处理一些特殊情况,例如,参数根本没有传递。好吧,
chunk?:any,encoding?:any
完成了这个技巧。chunk?:any,encoding?:string
仍返回错误……好吧,chunk?:any,encoding?:any
完成了这个技巧。chunk?:any,encoding?:string
仍在运行正在返回错误…的可能重复项的可能重复项