Skip to content

how do i schema.parse with returned type from schema? #1556

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

You must be logged in to vote

I think you need to use a generic. <Schema extends z.ZodType>

Let me know if you have any questions.

const inputSchema = z.object( {
    page: z.string().default( '1' ).transform( ( v ) => parseInt( v ) ),
    limit: z.string().default( '10' ).transform( ( v ) => parseInt( v ) ),
} )

export const parseTest = async <Schema extends z.ZodType> (
    schema: Schema, data: any
): Promise<z.infer<Schema>> => {
    return schema.parse( schema, data )
}

const aaa = await parseTest( inputSchema, { page: '1', limit: '10' } )
type AAA = typeof aaa
// type AAA = { page: number; limit: number; }

console.log( aaa ) // { page: 1, limit: 10 }

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by JacobWeisenburger
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