[英]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.