Problem with infering json type in zod schema
When using the following table/schema:
Am I doing something wrong? How can I pick the value key with correct types from the schema?
Solution:Jump to solution
The
.$type()
helper only works on the type level, it cannot change the runtime behavior. The schema validation happens at runtime, thus it doesn't know about your type. If you want to validate your json field according to your type, you would need to refine the insert schema, like this:
```ts
const TestInsertSchema = createInsertSchema, {
value: () => z.object({ a: z.string(), b: z.number() }),
});...1 Reply
Solution
The
.$type()
helper only works on the type level, it cannot change the runtime behavior. The schema validation happens at runtime, thus it doesn't know about your type. If you want to validate your json field according to your type, you would need to refine the insert schema, like this:
To make it a bit more convenient, you can extract the object schema into a variable and reuse it: