Skip to content

[Feature]: Make asymmetric matcher types more useful #13812

@benjaminjkraft

Description

@benjaminjkraft

🚀 Feature Proposal

Using Jest expect's asymmetric matchers (anything, arrayContaining, etc.) in typed contexts gets very annoying very fast. For example:

function expectTypedEqual<T>(a: T, b: T) { expect(a).toEqual(b) }

// type error:
// Argument of type 'number[]' is not assignable to parameter of type 'AsymmetricMatcher_2'.
//   Property 'asymmetricMatch' is missing in type 'number[]' but required in type 'AsymmetricMatcher_2'.
expectTypedEqual([1, 2, 3], expect.arrayContaining(3))

This is in some sense correct: expect.arrayContaining(3) is not, in fact, a number[]. But in practice you almost always want to use it as a number[]! The proposal here is that we should lie about the types, and say it returns a number[], because that allows for greater type-safety in practice.

Motivation

Right now, most places where matchers get used in vanilla jest are untyped: for example toEqual takes (unknown, unknown). But it would be nice to support a move towards having more typed assertions as suggested in #13334; and this would also be useful for a first-party when as I just proposed in #13811. (In fact, I've mainly run into this when using an internal version of when.)

Example

No response

Pitch

This can't really be done anywhere else, but doing it in jest is just a matter of deciding the new types are better than the old ones, and adding them! This is a breaking change, but in practice it seems unlikely that many people are using the existing (unexported) types in a rich way.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions