Handling Dynamic JSON Schema with TypeScript and Zod - Type Mismatch Issues
I'm prototyping a solution and I've been banging my head against this for hours... This might be a silly question, but I'm trying to validate dynamic JSON data using Zod in a TypeScript project, but I'm running into type mismatch issues. My JSON structure can vary based on user inputs, leading to runtime errors when the schema does not align with the incoming data. For instance, I have the following Zod schema: ```typescript import { z } from 'zod'; const userSchema = z.object({ id: z.string(), name: z.string(), age: z.number().optional(), email: z.string().email().optional(), }); ``` When I receive JSON data like this: ```json { "id": "123", "name": "John Doe", "age": "twenty" } ``` Zod correctly identifies that `age` should be a number, yet when I try to parse it, I get the following behavior: ``` ZodError: Invalid input at ZodNumber._parse (node_modules/zod/lib/index.js:1234:17) ``` I've tried wrapping the parsing in a try-catch block to handle these errors more gracefully, but I want to avoid these mismatches in the first place. Would it be better to include a `z.union` or `z.coerce` to handle this situation? If so, how would I implement that? Additionally, can someone clarify the best approach to dynamically generate schemas if there are multiple optional fields that can appear in the JSON? My current understanding is limited, and I'm open to guidance on best practices for handling such flexible structures with TypeScript and Zod. My development environment is Linux. How would you solve this? This is my first time working with Typescript 3.10. Has anyone dealt with something similar?