How to properly type a function that takes Jest's expect asymmetric matchers?

Viewed 29

I'm trying to create a generic function that takes asymmetric matchers but I've encountered two problems.

  • The AsymmetricMatcher<Sample> type seems to be incompatible with AsymmetricMatcher_2.
  • AsymmetricMatcher_2 is not exported and I cannot find any other way to get the return type of expect.anything(), I'm doing ReturnType<typeof expect.anything> as of now, but I'd rather import it from the package itself.

The fact that I'm finding difficulties typing this function makes me think that I'm using the wrong approach. What would be the correct way to type this function?

This is a minimum reproducible example:

import { expect } from '@jest/globals';
import type { AsymmetricMatcher } from 'expect';

const allMatch = <SampleType>(matchers: AsymmetricMatcher<SampleType>[]) => (value: unknown) => (
  matchers.forEach(matcher => expect(value).toStrictEqual(matcher))
);

allMatch<{}>([
  expect.anything(),
  expect.objectContaining({}),
]);

When compiled:

$ $(npm bin)/tsc --noEmit test.ts                                                                     
test.ts:11:3 - error TS2739: Type 'AsymmetricMatcher_2' is missing the following properties from type 'AsymmetricMatcher<{}>': sample, inverse, $$typeof, getMatcherContext

9   expect.anything(),
     ~~~~~~~~~~~~~~~~~

test.ts:12:3 - error TS2322: Type 'AsymmetricMatcher_2' is not assignable to type 'AsymmetricMatcher<{}>'.

10   expect.objectContaining({}),
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~


Found 2 errors in the same file, starting at: test.ts:9
0 Answers
Related