按照此处的说明操作:
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
?
最佳答案
node-fetch
没有实现完整的 Fetch API——只有一个 subset这在 Node.js 上是有意义的。
但是,createHttpLink
的可能性很小。使用那些未实现的部分。所以在这里禁用类型检查应该是安全的:
const link = createHttpLink({ uri: '/graphql', fetch: fetch as any });
可能值得向 Apollo 项目提出问题,要求他们将预期类型限制为实际使用的类型。
关于typescript - 调用 createHttpLink 时获取的类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62229153/