Skip to content

Can we avoid .nonempty() changing the inferred input type? #3040

Answered by JacobWeisenburger
Balinth asked this question in Q&A
Discussion options

You must be logged in to vote

TypeScript is doing what it's supposed to do here:

const schema = z.number().array().nonempty()

type NonEmptyArray = z.input<typeof schema>
// type NonEmptyArray = [number, ...number[]]

const foo = ( x: NonEmptyArray ) => { }
foo( [ 42 ] ) // ok
foo( [] )
//   ^^
// Argument of type '[]' is not assignable to parameter of type '[number, ...number[]]'.
//   Source has 0 element(s) but target requires 1.

If you truly want a compile time non empty array, then this is correct. But it seems you don't want your types to match your runtime values. Is that correct?

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Answer selected by JacobWeisenburger
Comment options

You must be logged in to vote
1 reply
@CiprianaM
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants
Converted from issue

This discussion was converted from issue #3035 on December 11, 2023 00:06.