Function to convert a property with a default value to an optional generic type

I created a function to validate FormData objects with Zod, using a generic type for flexibility across schemas.

Here's the validate function:

export function validate<T>(
    formData: FormData,
    schema: z.ZodSchema<T>
): { validatedData: T; errors: null } | { validatedData: null; errors: ActionErrors<T> } {
    const body = parseFormData(formData);
    const validated = schema.safeParse(body);

    if (!validated.success) {
        return {
            validatedData: null,
            errors: formatZodErrors<T>(validated.error),
        };
    }

    return { validatedData: validated.data, errors: null };
}

The issue is that the properties in schemas with default values set are being treated as optional when using the helper function.

For example, here is the schema used in the validate function:

export const createUserSchema = z.object({
    name: fullName(),
    email: email(),
    sendActivationEmail: z.boolean().default(true)
});

Intellisense indicates the property as optional

This behavior of returning optional properties doesn't seem logical. Any insights or assistance would be highly appreciated 😊.

It's worth mentioning that skipping the helper function and parsing the data directly in the action does not result in optional properties as expected.

Answer â„–1

Give this a try:

function verify<T extends z.ZodTypeAny>(
    data: FormData,
    pattern: T
) {
    const body = analyzeFormData(data);
    const validatedPattern = pattern.safeParse(body);

    if (!validatedPattern.success) {
        return {
            validatedData: null,
            errors: describeZodErrors<z.infer<T>>(validatedPattern.error),
        };
    }

    return { validatedData: validatedPattern.data as z.infer<T>, errors: null };
}

The explanation provided in the document is clear and concise. For more information, visit writing-generic-functions, inferring-the-inferred-type

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

Tips on continuously making calls to a backend API until receiving a successful response with status code 200

While working on my Angular project, I have encountered a situation where I need to make calls to a backend API. If the response is not 200 OK, I have to keep calling the API every 30 seconds until I receive a successful response. In Angular, I usually ca ...

Leveraging material ui's createStyles

I'm struggling to convert my css from a less file to material createStyles and I'm having trouble understanding how it works. I grasp the basics of createstyles but I'm having difficulty with my child selector. All I want is to be able to ...

Using 'cy.get' to locate elements in Cypress tutorial

Is there a way to search for one element, and if it's not found, search for another element? cy.get(@firstElement).or(@secondElement).click() Can I use a function similar to || in conditions for this scenario? ...

An error was encountered in the rxjs-compat module at operator/shareReplay.d.ts line 2, character 10: TypeScript error TS2305

Currently, I am in the process of upgrading a basic Angular skeleton application from version 5 to version 6. However, I have encountered an issue while attempting to run the application: ERROR in node_modules/rxjs-compat/operator/shareReplay.d.ts(2,10): ...

What is the best way to convert the javascript code into clojurescript?

Looking to utilize capacitor/app in order to determine the state (background or active) of my iOS app. My project is built on Clojurescript, so I need to convert the following javascript code into a clojurescript equivalent. Javascript import { App } fro ...

Troubleshooting Problems with Data Binding in Angular 6

After switching from Angular JS 1.6 to Angular 6, I encountered a problem while working on an app in Angular 6. The [(ngModel)]="number1" directive for 2-way data binding caused my component to stop rendering. When I switched to (ngModel), the component ...

Tips for keeping a specific key value pair as the final entry in a Typescript Object

My goal is to construct a Typescript Object that has a specific element with the key 'NONE' always positioned at the end. This arrangement is crucial for displaying the object in my HTML page with this value appearing last. I am seeking an implem ...

Reusing Angular routes across different modules for backbutton functionality

Insights on my Application (Angular 12): Comprises of 3 Modules, each containing an overview page with a list and specific detail pages Each route is assigned an area tag to identify the user's navigation within the module Goal for Angular´s RouteR ...

Can one bring in a JavaScript function using webpack?

I have a unique JS library called: say-my-greeting.js function SayMyGreeting (greeting) { alert(greeting); } Now I want to incorporate this function in another (.ts) file; special-class.ts import SayMyGreeting from './say-my-greeting.js' ex ...

Implementing Limited Results in Redis FT.SEARCH with TypeScript

Snippet of code: client.ft.SEARCH('license-index-json',"@\\$\\" + ".reservedForApplicationName:GSTest",{ LIMIT: { from: 0, to: 1 } }) Error message: An error occurred when trying t ...

Using MongoDB's C# driver's type discriminators to create a specialized generic class that inherits from a non-generic base class

I am attempting to store a collection of objects belonging to a generic class that inherits from a base class in MongoDB using the official C# driver. Here is my code structure: abstract class MyAbstractClass {} class MyGenericClass<T>: MyAbstract ...

Challenge: Visual Studio 2015 MVC6 and Angular 2 compilation issue - Promise name not found

Initially, I've made sure to review the following sources: Issue 7052 in Angular's GitHub Issue 4902 in Angular's GitHub Typescript: Cannot find 'Promise' using ECMAScript 6 How to utilize ES6 Promises with Typescript? Visual ...

Rxjs: Making recursive HTTP requests with a condition-based approach

To obtain a list of records, I use the following command to retrieve a set number of records. For example, in the code snippet below, it fetches 100 records by passing the pageIndex value and increasing it with each request to get the next 100 records: thi ...

Discover the power of working with asynchronous values in objects using the latest @if syntax in Angular 17

Previously, we were able to chain multiple async operations using *ngIf directives in Angular. This allowed us to avoid repeating the async pipe in the template and instead reuse them as a single subscription. With the introduction of the new @if syntax in ...

Develop a new entity utilizing Array in Javascript

let DaysArray: any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"] I am looking to transform the above array into an Object structure as shown below: let DaysObject: any = { time: { headerName: "" }, m ...

Change the boolean value of a checkbox to text before including it in a GET request to send to an API

Currently, I am working on a school project that involves creating a recipe search application using Angular for the frontend and Laravel for the backend. The application fetches recipes from the Edamam API. I am looking to implement a feature where users ...

Changes in tabs are discarded when switching between them within Material UI Tabs

I have been experiencing an issue with the Material UI tab component where changes made in tabs are discarded when switching between them. It seems that after switching, the tabs are rendered again from scratch. For example, let's say I have a textFie ...

Acquire XML documentation for overloaded functions in Typescript

Is it possible for an overloaded function in a subclass to automatically inherit the XML documentation from its base class? When hovering over myFunc I want to be able to see the documentation from the base class when I hover over myFunc, rather than ju ...

Firebase is storing object values as 'undefined'

My goal is to retrieve user details from my firebase database while using Ionic and Typescript. Here is how I add a user: addToDatabase(user: User) { let isInstructor = user.isInstructor == null ? false : user.isInstructor; this.afDB.list("/users/").push ...

Cordova's FileReader takes precedence over TypeScript's FileReader functionality

I encountered an issue when adding the cordova-plugin-file-transfer plugin, where I received the error message: reader.addEventListener is not a function. This problem arises due to Cordova FileReader class overriding typescript FileReader. How can this ...