Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript: FetchMockSandbox and native fetch have incompatible types #641

Open
FranciscoG opened this issue Jul 5, 2022 · 1 comment
Open

Comments

@FranciscoG
Copy link

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'.

I'm importing the type FetchMockSandbox from your client

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

versions I'm using:

  • fetch-mock@9.11.0
  • typescript@4.7.4

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

@gRizzlyGR
Copy link

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants