Skip to content

Coerce bigint throws TypeError instead of ZodError #1856

Discussion options

You must be logged in to vote

How about this?

const schema = z.object( {
    id: z.any().transform( ( value, ctx ) => {
        try {
            return BigInt( value )
        } catch ( error ) {
            ctx.addIssue( {
                code: 'invalid_type',
                expected: 'unknown',
                received: value,
                message: `Can't be parsed to BigInt`,
            } )
        }
    } ),
} )
console.log( schema.safeParse( { id: 42 } ).success ) // true
console.log( schema.safeParse( { id: '42' } ).success ) // true
console.log( schema.safeParse( { id: 'invalid' } ).success ) // false
console.log( schema.safeParse( {} ).success ) // false

Replies: 5 comments 8 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@marcus13371337
Comment options

@marcus13371337
Comment options

Comment options

You must be logged in to vote
6 replies
@JacobWeisenburger
Comment options

@marcus13371337
Comment options

@JacobWeisenburger
Comment options

@marcus13371337
Comment options

@JacobWeisenburger
Comment options

Answer selected by JacobWeisenburger
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
2 participants
Converted from issue

This discussion was converted from issue #1855 on January 11, 2023 14:25.