4

我正在尝试node-fetch在我的打字稿项目中使用请求,但我不明白如何修复编译错误或它实际上试图告诉我什么。

我已将所有包(包括全局 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
4

1 回答 1

13

在上面两位评论者的帮助/提示下(非常感谢),我设法找到了该错误的原因和解决方案:

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

const toJson = (response: Response): Promise<object> => {

the type definition for it can be found in lib.dom.d.ts

node-fetch instead is implementing it's own Response type from @types\node-fetch\index.d.ts

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:

import fetch, { Response } from 'node-fetch';
于 2019-07-04T22:56:32.453 回答