[英]How can I fix this type X is not assignable to type Y error in typescript?
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; 错误TS2322:类型'((块:任何,编码:任何)=>任何'不能分配给类型'{():void; (buffer: Buffer, cb?: Function): void; (缓冲区:缓冲区,cb ?:功能):空; (str: string, cb?: Function): void; (str:字符串,cb ?:功能):void; (str: stri...'. (str:stri ...'。
in @types/node/index.d.ts
end
method is described like this: 在@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;
What would be the correct type to fix this error? 解决此错误的正确类型是什么?
From what I can see, you intend to use one of the available overloads: end(data?: any, encoding?: string): void;
从我所看到的,您打算使用一种可用的重载: 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, eg where arguments are not passed at all. 并确保正确处理一些极端情况,例如根本没有传递参数的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.