Zod data structure featuring optional fields

Is there a more efficient way to define a Zod schema with nullable properties without repeating the nullable() method for each property? Currently, I have defined it as shown below:

const MyObjectSchema = z
  .object({
    p1: z.string().nullable(),
    p2: z.number().nullable(),
    p3: z.boolean().nullable(),
    p4: z.date().nullable(),
    p5: z.symbol().nullable(),
  })
  .partial();

Note: Using .Partial does not make object fields nullable.

Answer №1

Below is a handy function you can use to make all fields of the zod object nullable while preserving field types.

function makeFieldsNullable<TSchema extends z.AnyZodObject>(schema: TSchema) {
    const entries = Object.entries(schema.shape) as [keyof TSchema['shape'], z.ZodTypeAny][];

    const updatedFields = entries.reduce((acc, [key, value]) => {
        acc[key] = value.nullable();
        return acc;
    }, {} as {
        [key in keyof TSchema['shape']]: z.ZodNullable<TSchema['shape'][key]>
    });

    return z.object(updatedFields)
}

Example of how to use this function:

makeFieldsNullable(
  z.object({
    field1: z.string(),
    field2: z.number()
  }),
)

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

Dealing with Endless Loops in React TypeScript: What Happens When State is Set in Multiple Instances of the Same

I'm currently facing an issue where I have two instances of the same component being rendered: <div><Modal title='Login'/></div> <div><Modal title='Join'/></div> Within the component, based on ...

What is the process for setting up a node test launch configuration?

I have some "node 18 test runner" tests ready to be executed. I can run them using the following command: node --loader tsx --test tests/**/*.ts To debug these tests in vscode, I realized that I need to set up a configuration entry in my launch.json. But ...

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...

Encountering a syntax issue with pipeable operators in Angular Rxjs

I am currently in the process of rewriting this code snippet: Observable .merge(this.searchQuery$, this.lazyQuery$) .do(() => this.loadingPage()) .map(filter => this.buildURL("jaume", Config.security['appName'], filter)) .s ...

Commitments, the Angular2 framework, and boundary

My Angular2 component is trying to obtain an ID from another service that returns a promise. To ensure that I receive the data before proceeding, I must await the Promise. Here's a snippet of what the component code looks like: export class AddTodoCo ...

Maintain synchrony of the state with swiftly unfolding occurrences

I developed a custom hook to keep track of a state variable that increments based on the number of socket events received. However, when I tested by sending 10 simultaneous events, the total value of the state variable ended up being 6, 7, or 8 instead of ...

Utilize a fresh function in Angular to retrieve and store data from a URL into a variable

Currently, I am attempting to utilize Angular in order to retrieve data from a link upon clicking a button. As a newcomer to Angular with only 2 days experience, my knowledge is quite limited. What I aim to achieve is triggering the loading of JSON data w ...

Using Checkbox from material-UI to add and remove strikethrough on a to-do list task

const Todo: React.FC<ITodoProps> = (props) => { const [textInput, setTextInput] = useState(''); const { addTodo, userId, todosForUser, user, } = props; if (user == null) { return ( <Grid container={true} direction=&apo ...

Executing a child component function once the parent component data is loaded in Angular 5

In my project, I have a parent component called program-page.component where I am invoking a function to fetch some data. ngOnInit() { this.getProgress(); } getFirstProgramItem() { this._contentfulService.getProgramItem(4, 1) .then((programItem) = ...

Set up a TypeScript project with essential dependencies for creating multiple raw JavaScript output files

Currently, I am in the process of developing scripts for Bot Land, a real-time strategy game that offers a unique gameplay experience. Rather than controlling units traditionally with a mouse and keyboard, players code their bots using an API to engage in ...

In Ionic 2, any modifications made to the data model will only be reflected in the user interface after there is

Q) Why does my data seem to magically appear on the UI after interacting with it, even though I have made changes in the backend? For instance, when fetching and updating data bound to a list, such as: this._LocalStorageService.getClients().then( (data ...

Developing Your Own Local Variable in Angular with Custom Structural Directive ngForIn

I am hoping for a clear understanding of this situation. To address the issue, I developed a custom ngForIn directive to extract the keys from an object. It functions correctly with the code provided below: import {Directive, Input, OnChanges, SimpleChan ...

Angular File Upload Button Tutorial

English is not my first language, so please excuse any mistakes. I recently started learning Angular and I'm attempting to build a file upload button that lets users upload files based on dropdown menu options (such as USA States). Once uploaded, the ...

The file node_modules/angular2-qrscanner/angular2-qrscanner.d.ts has been detected as version 4, while version 3 was expected. Resolving symbol

We're encountering a Metadata error that is causing obstacles in our deployment process. This issue is preventing the execution of ng build. Below, you will find the configuration details along with the complete error trace. ERROR in Error: Metadata ...

When calling UIComponent.getRouterFor, a TypeScript error is displayed indicating the unsafe return of a value typed as 'any'

I have recently integrated TypeScript into my SAPUI5 project and am encountering issues with the ESLint messages related to types. Consider this simple example: In this snippet of code, I am getting an error message saying "Unsafe return of an any typed ...

Type of event target MouseEvent

I am currently working on a custom hook const hasIgnoredClass = (element: Element, ignoredClass: string) => (element.correspondingElement ? element.correspondingElement : element ).classList.contains(ignoredClass); const isInIgnoredElement = ( ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

Solutions for Utilizing Generic Mixins in Typescript

As a newcomer to Typescript, I have encountered an issue with mixins and generics. The problem became apparent when working on the following example: (Edit: I have incorporated Titian's answer into approach 2 and included setValue() to better showcas ...

Extracting PDF files using API within Angular services

I have set up a Java-based API on a server, with the URL being "ex.com". This API has an endpoint that returns a PDF file, with the URL set as "ex.com/pdf". For this endpoint, a POST request is required with a parameter specifying the requested PDF, like ...

Accessing an Array from a service method in Angular and passing it to my main component

Within my api-service.ts, I have an array that holds some data. public getData():Observable<any[]> { return Observable.toString[ObsResult]; } Now, in the main component, I am attempting to call the getData() method to render the data in ...