Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i use native fetch with node in typescript (node v17.6)

In the console, when running node --experimental-fetch the fetch command is now natively enabled (node version >=17.6). see below

native fetch with node

However, when I add a typescript layer, I always get error TS2304: Cannot find name 'fetch'.

how can I solve this?

background idea: use fetch natively and get rid of node-fetch and @types/node-fetch dependencies

tsconfig.json and general setup: https://github.com/nexys-system/server-boilerplate/blob/master/tsconfig.json

see also:

like image 597
John Avatar asked Nov 20 '25 18:11

John


1 Answers

Please don't import the whole lib dom from the typescript package or add the node-fetch package for types as some people do. Cause ...

  1. Importing lib dom adds a lot of things to your globals that aren't available in node environments.
  2. Adding the node-fetch to your project only for types, adds only the required types, but sadly they aren't complaint to the W3C fetch() specs. See: https://github.com/node-fetch/node-fetch/blob/main/docs/v3-LIMITS.md

What is somehow correct indeed, is to import the package "undici". As this package is the base for node's fetch() implementation, it provides the correct types. Source: https://nodejs.org/de/blog/announcements/v18-release-announce/#fetch-experimental

I recommend adding a .d.ts file to your project, with the following content:

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

This obviously requires you to install the package 'undici' as well via your package manager of choice! https://www.npmjs.com/package/undici

For the ones super interested in this, there is a discussion ongoing in the DefinitelyTyped repository on github about it: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/60924

like image 137
Ruben Avatar answered Nov 25 '25 00:11

Ruben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!