jest test.each types not matching: typescript fix
Fixes TypeScript type errors in jest `test.each` parameterized tests. Use it when row values do not match the callback signature. Not for runtime test.each failures or non-TypeScript jest issues.
TL;DR
test.each infers row types from the table, and the inference often comes out wider or narrower than your callback expects, especially with mixed-type rows or template-literal tables. The reliable fix is to type the table explicitly: use as const on array tables, or annotate the callback parameters, so the row type and the callback signature agree. When the table has heterogeneous rows, type it as a tuple union instead of letting inference widen everything to string | number.
The query
jest test.each types not matching: typescript fixUse this when
- TypeScript errors inside
test.eachcallbacks about argument types - Template-literal tables (
test.each\...\`) givingstring` where you need numbers - Refactoring a test table breaks type checking but tests still run
Not for
- Runtime failures in parameterized tests
- Plain JavaScript
test.eachusage - Jest type errors outside
test.each
Steps
- Read the exact TS error on the callback parameters and compare with the inferred table row type (hover the table in your editor). Expected output: you see the mismatch, e.g. rows inferred as
(string | number)[]while the callback wants[string, number]. - Type the table explicitly: add
as constto array tables, or declare the row tuple type and annotate the table with it. Expected output: the table's inferred type now matches the callback signature. - For template-literal tables, convert values at the row level or switch to an array table when you need non-string types. Expected output: numeric/boolean columns keep their types instead of widening to string.
- Run
tsc --noEmit(or your typecheck) and then the tests. Expected output: type errors gone, tests still green.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_G6fahn8oCYoP1lDtBmDNiw
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.