调用 createHttpLink 时获取的类型不匹配

pup*_*eno 3 typescript apollo server-side-rendering

按照此处的说明操作:

https://www.apollographql.com/docs/react/performance/server-side-rendering/#server-side-rendering

做服务器端渲染我遇到了这个错误:

Invariant Violation:
fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/node-fetch.

For example:
import fetch from 'node-fetch';
import { createHttpLink } from 'apollo-link-http';

const link = createHttpLink({ uri: '/graphql', fetch: fetch });
Run Code Online (Sandbox Code Playgroud)

我添加了推荐的代码,导入fetch,将它传递给createHttpLink,我也安装了@types/node-fetch,但我收到了这个警告/错误:

Error:(75, 7) TS2322: Type 'typeof fetch' is not assignable to type '(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>'.
  Types of parameters 'url' and 'input' are incompatible.
    Type 'RequestInfo' is not assignable to type 'import("C:/Users/pupeno/Documents/Flexpoint Tech/js/exp5/node_modules/@types/node-fetch/index").RequestInfo'.
      Type 'Request' is not assignable to type 'RequestInfo'.
        Type 'Request' is missing the following properties from type 'Request': context, compress, counter, follow, and 6 more.
Run Code Online (Sandbox Code Playgroud)

我传递的 fetch 函数的类型定义node-fetch/index.d.ts为:

declare function fetch(
    url: RequestInfo,
    init?: RequestInit
): Promise<Response>;
Run Code Online (Sandbox Code Playgroud)

而预期的类型fetch是:

fetch?: WindowOrWorkerGlobalScope['fetch'];
Run Code Online (Sandbox Code Playgroud)

我不确定如何找到WindowOrWorkerGlobalScope,我的 IDE 指向两个可能的定义,一个在dom

fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
Run Code Online (Sandbox Code Playgroud)

和一个webworker

fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
Run Code Online (Sandbox Code Playgroud)

他们看起来完全一样。

我可以继续深入各种类型的兔子洞,但这是否敲响了警钟?我应该使用不同的fetch吗?

Lam*_*iry 5

node-fetch没有实现完整的 Fetch API——只是一个在 Node.js 上有意义的子集

但是,createHttpLink使用那些未实现的部分的可能性很小。所以在这里禁用类型检查应该是安全的:

const link = createHttpLink({ uri: '/graphql', fetch: fetch as any });
Run Code Online (Sandbox Code Playgroud)

可能值得向 Apollo 项目提交问题,要求他们将预期类型限制为实际使用的类型。