我正在尝试使用 node-fetch
发出请求在我的 typescript 项目中,我不明白如何修复编译错误或它实际上试图告诉我什么。
我已将所有包(包括全局 typescript 包)更新到最新版本。
我创建了一个隔离错误的要点:https://gist.github.com/HerrZatacke/ae90f608e042864b6e00e9c73a950602
这个(非常短的)脚本能够重现编译错误:
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();
使用的安装版本是
@types/node-fetch 2.3.7
node-fetch2.6.0
typescript 3.5.2
实际错误是
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
最佳答案
在上面两位评论者的帮助/提示下(非常感谢),我设法找到了该错误的原因和解决方案:
Typescript 最初尝试“猜测”您正在使用的类型。
以下行说明我想使用类型 response
, 这是原生 Fetch API 的接口(interface)
const toJson = (response: Response): Promise<object> => {
它的类型定义可以在 lib.dom.d.ts 中找到。
node-fetch
而是实现它自己的 Response
输入来自 @types\node-fetch\index.d.ts因此,如果首先导入正确的响应类型,则 typescript 编译器运行时不会出错。
这意味着,而不是仅仅导入
node-fetch
, 你还必须导入它的定义 Response
:import fetch, { Response } from 'node-fetch';
关于node.js - 如何修复 Typescript 编译错误 ts2345 "Type ' 响应'丢失......来自类型 'Response' : redirected, 预告片,formData!”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56877355/