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

问题描述 投票:0回答:1

按照此处的说明:

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 });

我添加了推荐的代码,导入了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.

我正在传递的获取函数的类型,在node-fetch/index.d.ts上定义为:

declare function fetch(
    url: RequestInfo,
    init?: RequestInit
): Promise<Response>;

fetch的预期类型是:

fetch?: WindowOrWorkerGlobalScope['fetch'];

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

fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;

webworker中的一个:

fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;

它们看起来相同。

我可以继续沿着类型的兔子洞走,但这会打铃吗?我应该使用其他fetch吗?

typescript apollo server-side-rendering
1个回答
0
投票

[node-fetch并未实现完整的Fetch API,仅实现了对Node.js有意义的subset

但是,createHttpLink不太可能使用那些未实现的部分。因此,在此处禁用类型检查应该是安全的:

const link = createHttpLink({ uri: '/graphql', fetch: fetch as any });

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

© www.soinside.com 2019 - 2024. All rights reserved.