I am currently working on a project that involves using drizzle-orm and zod for validation in a TypeScript environment. My issue arises from the interaction between these two libraries, specifically when dealing with the InsertOrderType type provided by drizzle-orm. Here's the relevant code snippet:

// From drizzle schema export type InsertOrderType = InferModel<typeof orderSchema, "insert">; 

The InsertOrderType type works well with drizzle-orm, but I need to manually calculate the "amount" field for security reasons and exclude it from the zod validation schema. Here's my zod validation schema:

import * as z from 'zod'; const orderSchema = z.object({ // ... other fields ... // 'amount': How can I exclude this field from here? }); 

Now, since the "amount" field is missing from the zod validation schema, my InsertOrderType is throwing type errors due to the missing "amount" field.

I've tried setting "amount" as optional in the zod validation schema, but this approach doesn't seem to work as it still complains about missing "amount" in the InsertOrderType.

How can I handle this situation properly? Am I approaching this the wrong way with TypeScript types? Is there a way to exclude the "amount" field from the zod validation schema while still keeping it compatible with drizzle-orm? Any help or guidance would be greatly appreciated.

1 Answer

Generally speaking, Zod is helping you with user input validation. It makes sure the value is set and satisfies certain criteria. You nonetheless should read, and properly validate, or override with a backend calculation logic, to make sure the value is "correct" before inserting into your DB. This isn't necessary an ORM/Zod issue, but rather how you handle your backend logic.


If you want to make a required field optional (if I understood your question correctly), see below:

Ideally you Pick the fields you need, but in the case where you only need to make one field optional, you can do so by merging two schemas. A.merge(B), where keys in B override keys in A

Below solution should likely satisfy your requirements

const orderSchema = z.object({ // ... other fields ... // 'amount': How can I exclude this field from here? }).merge(z.object({ amount: z.number().optional() })); 

Zod merge docs

From the docs

If the two schemas share keys, the properties of B overrides the property of A. The returned schema also inherits the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B.

5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.