Error involving TypeScript when using drizzle-orm in conjunction with zod validation

In my current project, I am utilizing drizzle-orm and zod for validation within a TypeScript environment. The issue I am facing lies in the interaction between these two libraries, specifically when working with the InsertOrderType type provided by drizzle-orm. Here is the relevant code snippet:

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

While the InsertOrderType type functions well with drizzle-orm, I require manual calculation of the "amount" field for security reasons and need to exclude it from the zod validation schema. Below is my zod validation schema:

import * as z from 'zod';

const orderSchema = z.object({
  // ... other fields ...
  // How can I remove "amount" field from this schema?
});

As the "amount" field is not present in the zod validation schema, I am encountering type errors with the InsertOrderType due to the absence of the "amount" field.

I have attempted to mark "amount" as optional in the zod validation schema, but this method does not resolve the issue as it still raises concerns about the missing "amount" in the InsertOrderType.

How should I handle this scenario effectively? Could I be taking the wrong approach with TypeScript types? Is there a way to eliminate the "amount" field from the zod validation schema while maintaining compatibility with drizzle-orm? Any assistance or advice would be highly appreciated.

Answer №1

In a general sense, Zod plays a role in assisting with user input validation by ensuring that the value is both present and meets certain criteria. However, it is still important for you to thoroughly review and validate, or potentially replace, with backend calculation logic to ensure that the value is deemed "correct" before inserting it into your database. This issue does not necessarily stem from an ORM/Zod conflict, but rather hinges on how you manage your backend logic.


If you are looking to convert a required field into an optional one (if my understanding of your question is correct), see the following solution:

It is recommended that you use the Pick method to select the necessary fields, however if you only need to make a single field optional, you can achieve this by combining two schemas. By using A.merge(B), where the keys in B take precedence over those in A,

The proposed solution outlined below should meet your needs satisfactorily

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

Further information on Zod merge functionality

Based on the documentation

If the two schemas contain overlapping keys, the properties of B will override those of A. The resulting schema will also inherit the "unknownKeys" policy (strip/strict/passthrough) and the catchall schema of B.

Answer №2

Apologies for the unrelated response. I just need 2 more reputation points before I can leave a comment.

While Michael's answer is spot on, I'm curious if there might be some confusion about the removal of unspecified properties when using parse.

If you make the amount optional in the initial validation, it won't be stripped and will remain accessible in the subsequent steps. However, using safeParse might be more beneficial to obtain the validation result without any stripping functionality.

Take note of how parse clones the input to ensure that the inferred type matches what was declared.

This information could benefit someone - Zod is an exceptional library with great power when utilized correctly to fulfill your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The method getDay is not recognized as a function in Typescript Angular

After searching for a solution, I came across a similar question that did not address the specific issue I am dealing with. The challenge I am facing involves parsing a date into a string. Below is my current implementation: export class DataFormater { ...

Comprehending TypeScript: Dealing with parameters that cannot be assigned

Let's consider the following scenario: const client: Client | boolean = await db.connect() if (client === false) { return } await start(client) The function db.connect() returns either a Client on successful connection or false in case of failure ...

Leverage the power of JavaScript functions within the app.component.ts file of

I have a JavaScript file named action.js and I am trying to incorporate it into an Angular project. After doing some research, I found out that the js file should be placed in the assets folder and the path must be referenced in the scripts array within an ...

Inconsistencies in AngularJS ng-checked functionality

Currently, I am utilizing angularjs in conjunction with an edit view for a form. My goal is to bind the values that were previously used. Below is the code/HTML snippet that I am working with. In addition to angularjs, I am also implementing typescript fol ...

Send information as FormData object

I'm getting the data in this format: pert_submit: {systemId: "53183", pert-id: "176061", score: 0, q2c: "3\0", q2t: "", …} Now I need to send it as FormData in my post request. Since I can't use an ...

How do React Native proxies differ from vanilla React proxies in their functionality?

Trying to retrieve data from an API running locally on port 5000 of my device, I recalled setting the proxy in package.json when working on React web applications: "proxy": "https://localhost:5000" Attempting to fetch information f ...

Angular 6 ActivatedRoute Parameters

I'm having trouble retrieving the data of each record using ActivatedRoute. I've been able to get the ID for each one, but I can't seem to access the other data. Any suggestions? Check out my stackblitz example: https://stackblitz.com/edit/ ...

Learning to implement forwardRef in MenuItem from Material-UI

Encountering an error when pressing Select due to returning MenuItem in Array.map. Code const MenuItems: React.FC<{ items: number[] }> = (props) => { const { items } = props; return ( <> {items.map((i) => { return ( ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

Angular8 with the [tinymce] library for customizing editor elements and configuring multiline options

I am currently working with Angular 8 and in the template, we have the following code snippet: <editor required class="research-modal__control__input research-modal__control__input__description" formCo ...

Is there a way to prompt TypeScript to report an error when a mapped key is missing?

Here is my current code snippet: type TransferType = 'INTERNAL' | 'WITHDRAWAL' | 'DEPOSIT' type TransferEvents = Record<TransferType, Record<string, TypeFoo | TypeBar>> export interface EventsTooltip extends Tran ...

Is there a way to store my Typeorm data source configuration in a separate variable?

I am currently working with NestJS 10 and TypeORM 0.3.17. In my src/config/data-source.ts file, I have the following code snippet... import * as dotenv from 'dotenv'; import * as dotenvExpand from 'dotenv-expand'; import { DataSource } ...

One function must pause and await the outcome of another function

I am developing a form that utilizes the data of the currently logged in user. The function responsible for setting the value of the form is executed before retrieving the user data. ngOnInit() { this.auth.getUserState() .subscribe( user => { ...

Angular 2 Google Chart: Defining column type using TypeScript

I am currently attempting to implement the Timeline chart functionality from the angular2-google-chart module for Google Charts. Unlike the other examples provided, this specific chart type requires a column type definition — a requirement not present in ...

The 'palette' property is not found on the Type 'Theme' within the MUI Property

Having some trouble with MUI and TypeScript. I keep encountering this error message: Property 'palette' does not exist on type 'Theme'.ts(2339) Check out the code snippet below: const StyledTextField = styled(TextField)(({ theme }) = ...

Is it possible to transform a personalized typescript component into an HTMLElement within the Angular framework?

Suppose I have a customized component named 'my-component' in Angular. Is there a method to transform this component into a HTMLElement so it can be passed to a function that requires a HTMLElement as an argument? I am aware that the HTMLElemen ...

What is the reason behind the Typescript compiler not converting .ts files to .js files automatically?

Displayed below are the folders on the left showcasing my Typescript file in /src (blue) compiled into Javascript in /dist (purple) using tsc. https://i.stack.imgur.com/7XNkU.png In the source file on the left, there is a reference to a .ts module file t ...

Child router receives subscription from parent router

Is there a way to trigger events on every URL change within a child router? I have been able to implement event firing on URL changes within the main router using the following code, but I am struggling with achieving this in a child router. I'm curr ...

Indicate a specific type for the Express response

Is there a method to define a specific type for the request object in Express? I was hoping to customize the request object with my own type. One approach I considered was extending the router type to achieve this. Alternatively, is there a way to refactor ...

What does `(keyof FormValues & string) | string` serve as a purpose for?

Hey there! I'm new to TypeScript and I'm a bit confused about the purpose of (keyof FormValues & string) | string. Can someone please explain it to me? export type FieldValues = Record<string, any>; export type FieldName<FormValues ...