[英]Typescript error TS2345 Error: TS2345:Argument of type 'Buffer' is not assignable to parameter of type 'string'
[英]How to fix Typescript compilation error ts2345 “Type 'Response' is missing … from type 'Response': redirected, trailer, formData!”
我试图在我的打字稿项目中使用node-fetch
发出请求,但我不明白如何解决编译错误或它实际上试图告诉我什么。
我已经将所有软件包(包括全局打字稿软件包)更新为最新版本。
我创建了一个隔离错误的要点: 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
借助以上两个评论者的帮助/提示(非常感谢),我设法找到了该错误的原因和解决方案:
打字稿最初尝试“猜测”您正在使用的类型。
以下行状态我想使用类型response
,它是本机Fetch API的接口
const toJson = (response: Response): Promise<object> => {
它的类型定义可以在lib.dom.d.ts中找到
node-fetch
而是从@types \\ node-fetch \\ index.d.ts实现它自己的Response
类型
因此,如果首先导入正确的响应类型,则打字稿编译器将运行而不会出现错误。
这意味着,不仅要导入node-fetch
,还必须导入它的Response
的定义:
import fetch, { Response } from 'node-fetch';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.