我如何在打字稿中使用本机获取和节点(节点v17.6)

Joh*_*ohn 18 node.js fetch-api

在控制台中,运行命令时node --experimental-fetch现在fetch已本机启用(节点版本 >=17.6)。见下文

使用节点进行本机获取

但是,当我添加打字稿层时,我总是得到error TS2304: Cannot find name 'fetch'.

我该如何解决这个问题?

背景思想:本地使用 fetch 并摆脱node-fetch依赖@types/node-fetch关系

tsconfig.json和一般设置:https ://github.com/nexys-system/server-boilerplate/blob/master/tsconfig.json

也可以看看:

小智 18

请不要像某些人那样从 typescript 包中导入整个 lib dom 或为类型添加 node-fetch 包。原因 ...

  1. 导入 lib dom 会向全局变量添加许多在节点环境中不可用的内容。
  2. 仅针对类型将节点获取添加到项目中,仅添加所需的类型,但遗憾的是它们不符合 W3C fetch() 规范。请参阅:https ://github.com/node-fetch/node-fetch/blob/main/docs/v3-LIMITS.md

确实在某种程度上正确的是导入包“undici”。由于此包是节点 fetch() 实现的基础,因此它提供了正确的类型。来源:https ://nodejs.org/de/blog/announcements/v18-release-announce/#fetch-experimental

我建议向您的项目添加一个 .d.ts 文件,其中包含以下内容:

import * as undici_types from 'undici';

declare global {
  export const {
    fetch,
    FormData,
    Headers,
    Request,
    Response,
  }: typeof import('undici');

  type FormData = undici_types.FormData;
  type Headers = undici_types.Headers;
  type HeadersInit = undici_types.HeadersInit;
  type BodyInit = undici_types.BodyInit;
  type Request = undici_types.Request;
  type RequestInit = undici_types.RequestInit;
  type RequestInfo = undici_types.RequestInfo;
  type RequestMode = undici_types.RequestMode;
  type RequestRedirect = undici_types.RequestRedirect;
  type RequestCredentials = undici_types.RequestCredentials;
  type RequestDestination = undici_types.RequestDestination;
  type ReferrerPolicy = undici_types.ReferrerPolicy;
  type Response = undici_types.Response;
  type ResponseInit = undici_types.ResponseInit;
  type ResponseType = undici_types.ResponseType;
}
Run Code Online (Sandbox Code Playgroud)

这显然需要您通过您选择的包管理器安装包“undici”! https://www.npmjs.com/package/undici

对于对此超级感兴趣的人,github上的DefinitelyTyped存储库正在进行有关它的讨论: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/60924


zVi*_*tor 14

目前只有 2 个简单/懒惰的解决方案(检查Ruben 的答案以找到合适的解决方案):

  1. 您可以"lib": ["dom"]在您的tsconfig.json
  2. 您可以/// <reference lib="dom" />在您使用的文件的顶部添加fetch

我个人更喜欢#2,因为我可以更轻松地跟踪我在哪里使用这个技巧。

请注意,“这告诉 TypeScript 您打算在浏览器环境中运行此代码,从而允许您使用 DOM 特定的全局变量。这使得类型检查更加宽松,并可能导致意外的运行时错误”。

  • 这是一个错误的答案!正如其他人指出的那样,这告诉 TypeScript 您打算在浏览器环境中运行此代码,从而允许您使用特定于 DOM 的全局变量。这使得类型检查更加宽松,并可能导致意外的运行时错误。 (8认同)