【问题标题】:How can I fix this type X is not assignable to type Y error in typescript?如何修复此类型 X 不可分配给打字稿中的类型 Y 错误?
【发布时间】:2018-03-21 20:35:06
【问题描述】:

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

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; (缓冲区:缓冲区,cb?:函数):无效; (str: string, cb?: Function): void; (str:stri ...'。

@types/node/index.d.tsend方法中是这样描述的:

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;

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

【问题讨论】:

标签: typescript express


【解决方案1】:

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

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

使用

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

并确保您正确处理极端情况,例如根本不传递参数。

【讨论】:

  • 好吧,chunk?:any, encoding?:any 成功了。 chunk?:any, encoding?:string 仍然返回错误...
猜你喜欢
  • 2021-03-02
  • 2021-12-06
  • 2017-12-12
  • 2018-02-02
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 1970-01-01
相关资源
最近更新 更多