Skip to content

expect.any and expect.anything should return something more specific than any #7015

@JoshuaKGoldberg

Description

@JoshuaKGoldberg

Describe the bug

expect.any() and expect.anything() are typed as returning any right now:

anything: () => any
any: (constructor: unknown) => any

any is generally not particularly type safe. unknown is the safer equivalent. AFAIK there's no reason why an external consumer of Vitest would want the more permissive, less safe any here instead of unknown.

Proposal: purely as a type system change, can we switch those two any types to unknown?

I sent #7016 as a draft for reference.

Reproduction

The main reason I'm filing this is because the unsafe any-ness gets picked up by @typescript-eslint/no-unsafe-assignment in some cases.

https://github.com/JoshuaKGoldberg/repros/tree/repro-vitest-expect-any-tseslint-no-unsafe-assignment

In a nutshell, these value: ... lines are the issue:

const logger = vi.fn();

expect(logger).toHaveBeenCalledWith({
  value: expect.any(Object),
});

expect(logger).toHaveBeenCalledWith({
  value: expect.anything(),
});

Just to be thorough, here's what you get if you console.log the two in that order:

Any {
  '$$typeof': Symbol(jest.asymmetricMatcher),
  sample: [Function: Object],
  inverse: false
}
Anything {
  '$$typeof': Symbol(jest.asymmetricMatcher),
  sample: undefined,
  inverse: false
}

System Info

n.b. only `npmPackages` is relevant here; this is just in the type system. 

  System:
    OS: macOS 13.2
    CPU: (10) arm64 Apple M1 Max
    Memory: 535.77 MB / 32.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 22.4.1 - ~/.nvm/versions/node/v22.4.1/bin/node
    Yarn: 1.22.19 - ~/.yarn/bin/yarn
    npm: 10.8.1 - ~/.nvm/versions/node/v22.4.1/bin/npm
    pnpm: 9.12.3 - ~/.nvm/versions/node/v22.4.1/bin/pnpm
  Browsers:
    Chrome: 131.0.6778.86
    Safari: 16.3
  npmPackages:
    vitest: ^2.1.8 => 2.1.8

Used Package Manager

npm

Validations

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