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

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:
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 ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With