Access the list of valid options inside the error message without typescript complaining #1621
Answered
by
JacobWeisenburger
JacobWeisenburger
asked this question in
Q&A
-
I have a list of options that I want to validate, but when an incorrect value is put in, then the error is not very helpful. So I am trying to write my own error messages. But there seems to be no way to access the list of valid options inside the error message without typescript complaining. When I ignore the ts errors, it runs just fine. So what am I doing wrong? export const unionOfLiteralsSchema = z.union( [
// ^^^^^^^^^^^^^^^^^^^^^
// 'unionOfLiteralsSchema' implicitly has type 'any' because it does not have a
// type annotation and is referenced directly or indirectly in its own initializer.
z.literal( 'item 1' ),
z.literal( 'item 2' ),
z.literal( 'item 3' ),
], {
errorMap: ( issues, ctx ) => ( {
message: `${ ctx.data } is not a valid option.
Please choose a valid option: ${ unionOfLiteralsSchema.options.map( o => o.value ) }`,
} )
} )
export const enumSchema = z.enum( [
// ^^^^^^^^^^
// 'enumSchema' implicitly has type 'any' because it does not have a
// type annotation and is referenced directly or indirectly in its own initializer.
'item 1',
'item 2',
'item 3',
], {
errorMap: ( issues, ctx ) => ( {
message: `${ ctx.data } is not a valid option.
Please choose a valid option: ${ enumSchema.options }`,
} )
} ) |
Beta Was this translation helpful? Give feedback.
Answered by
JacobWeisenburger
Dec 5, 2022
Replies: 1 comment
-
I ended up figuring it out later. I still can't seem to figure it out for a union of literal strings though. const enumSchema = z.enum( [
'item 1',
'item 2',
'item 3',
], {
errorMap: ( issue, ctx ) => {
if ( issue.code === 'invalid_enum_value' ) return ( {
message: `${ ctx.data } is not a valid option.
Please choose a valid option: ${ issue.options }`,
} )
return { message: ctx.defaultError }
}
} ) |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
JacobWeisenburger
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I ended up figuring it out later.
I still can't seem to figure it out for a union of literal strings though.