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

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

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

相关文章:

typescript - 在 TypeScript 中获取 "HTMLInputElement"类型

javascript - 如何在angular2 webpack typescript 中包含第三方javascript库

javascript - "Could not find a declaration file for module"导入现有 .jsx 文件时

graphql - 为什么我的 Apollo 缓存更新没有反射(reflect)在我的查询中?

reactjs - React Apollo : One query, 多个参数 - 如何缓存?

javascript - 如何在 React 中使用 React 可加载和获取组件数据(如 Next.js)进行服务器端渲染?

node.js - 用于带有 sails 的 React-Redux 应用程序的 SSR

javascript - Angular/TypeScript Map 在每个对象上使用最后一个索引

用于 C++ 和 .NET 的 GraphQL 客户端

reactjs - React 样板中的服务器端渲染