fetch-mock icon indicating copy to clipboard operation
fetch-mock copied to clipboard

Typescript: FetchMockSandbox and native fetch have incompatible types

Open FranciscoG opened this issue 3 years ago • 1 comments

TLDR

FetchMockSandbox is supposed to be a drop-in replacement for fetch except that their types are incompatible

FetchMockSandbox's first argument input has a ? which allows it to be undefined, native fetch does not.


I have a function which accepts the fetch method as a parameter.

export const handleFetch = (fetchMethod: typeof fetch): void => {
  // code  
}

I should be able to also pass in a FetchMockSandbox to this function but typescript says that FetchMockSandbox and native fetch are incompatible:

error TS2345: Argument of type 'FetchMockSandbox' is not assignable to parameter of type '(input: URL | RequestInfo, init?: RequestInit | undefined) => Promise<Response>'.

I'm importing the type FetchMockSandbox from your client

import fetch_mock, { FetchMockSandbox } from 'fetch-mock/esm/client'

versions I'm using:

This is the type info for fetch and RequestInfo (inspecting types via vscode)

function fetch(input: RequestInfo | URL, init?: RequestInit | undefined): Promise<Response>
// and
type RequestInfo = Request | string;

When I inspect the FetchMockSandbox type I see this:

interface FetchMockSandbox extends FetchMockStatic {
        /**
         * Also callable as fetch(). Use `typeof fetch` in your code to define
         * a field that accepts both `fetch()` and a fetch-mock sandbox.
         */
        (input?: string | Request , init?: RequestInit): Promise<Response>;
    }

I'm following your instructions from your own type definition and it does not work

typeof fetch and FetchMockSandbox are not compatible

FranciscoG avatar Jul 05 '22 15:07 FranciscoG

This is how I solved:

import fetch from 'node-fetch';
import fm from 'fetch-mock';

type Fetch = typeof Fetch;
type FetchMock = fm.FetchMockSandbox & Fetch;

const fetchMock = fm.sandbox() as FetchMock;

gRizzlyGR avatar Mar 13 '24 15:03 gRizzlyGR

I won't be fixing this as I'm working on a totally new implementation, @fetch-mock/core, which does not have the .sandbox() functionality

wheresrhys avatar Jul 20 '24 12:07 wheresrhys