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 ...
- Importing lib dom adds a lot of things to your globals that aren't available in node environments.
- 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