[英]How to fix Typescript compilation error ts2345 “Type 'Response' is missing … from type 'Response': redirected, trailer, formData!”
I am trying to make a request using node-fetch
in my typescript project and I do not understand how to fix the compilation error or what it actually tries to tell me. 我试图在我的打字稿项目中使用node-fetch
发出请求,但我不明白如何解决编译错误或它实际上试图告诉我什么。
I've updated all packages (including the global typescript package) to the latest versions. 我已经将所有软件包(包括全局打字稿软件包)更新为最新版本。
I've created a gist that isolates the error: https://gist.github.com/HerrZatacke/ae90f608e042864b6e00e9c73a950602 我创建了一个隔离错误的要点: https : //gist.github.com/HerrZatacke/ae90f608e042864b6e00e9c73a950602
This (very short) script is able to reproduce the compilation error: 这个(很短的)脚本能够重现编译错误:
import fetch from 'node-fetch';
const toJson = (response: Response):PromiseLike<object> => (
response.json()
);
const makeSomeRequest = (): Promise<object> => {
return fetch('https://some-api.com/')
.then(toJson)
};
makeSomeRequest();
The installed versions used are 使用的安装版本是
@types/node-fetch 2.3.7
node-fetch2.6.0
typescript 3.5.2
the actual error is 实际错误是
example.ts:9:11 - error TS2345: Argument of type '(response: Response) => PromiseLike<object>' is not assignable to parameter of type '(value: Response) => object | PromiseLike<object>'.
Types of parameters 'response' and 'value' are incompatible.
Type 'Response' is missing the following properties from type 'Response': redirected, trailer, formData
With the help/hints of the two commenters above (thanks a lot), I managed to find the reason and a solution for that error: 借助以上两个评论者的帮助/提示(非常感谢),我设法找到了该错误的原因和解决方案:
Typescript initially tries to "guess" which types you are using. 打字稿最初尝试“猜测”您正在使用的类型。
The following line states I want to use the type response
, which is an interface of the native Fetch API 以下行状态我想使用类型response
,它是本机Fetch API的接口
const toJson = (response: Response): Promise<object> => {
the type definition for it can be found in lib.dom.d.ts 它的类型定义可以在lib.dom.d.ts中找到
node-fetch
instead is implementing it's own Response
type from @types\\node-fetch\\index.d.ts node-fetch
而是从@types \\ node-fetch \\ index.d.ts实现它自己的Response
类型
So, if the correct response type is being imported first, the typescript compiler runs without the error. 因此,如果首先导入正确的响应类型,则打字稿编译器将运行而不会出现错误。
Which means, instead of just importing node-fetch
, you also have to import it's definition of Response
: 这意味着,不仅要导入node-fetch
,还必须导入它的Response
的定义:
import fetch, { Response } from 'node-fetch';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.