The "shape" property is not available while utilizing generics with toZod

Short version: I encountered a type error, and here is the link to the TS PLAYGROUND

I am looking to ensure type safety when creating zod schemas. To achieve this, I define the data type like so:

type Option = { id: number };

Using this type definition helps me specify the exact keys for my zod object schema, with the help of toZod to transform the datatype number into z.number().

For instance, below is a function that generates an option schema (const test1 = createOptionSchema({id: z.number()}) const test2 = createOptionSchema({id: z.number().int()})

const test3 = createOptionSchema({id: z.string()})
const test4 = createOptionSchema({name: z.number()})
const test5 = createOptionSchema({id: z.number().optional()})

Currently, this function only supports the Option type. I aim to use the same function for all data types, so I made this modification:


function createSchema<T extends Record<string, unknown>>(input: {
  [K in keyof T]: toZod<T>["shape"][K];
}) {
  const Schema: toZod<T> = z.object(input);

  return Schema;
}

However, now I am encountering this error:

Type '"shape"' cannot be used to index type 'toZod<T>'

Despite trying different approaches, I couldn't find a solution yet. Do you have any ideas?

Helpful links:

I attempted using a custom type to replace the toZod type but struggled to convert types into zod schema types.

I also experimented with satisfies, but it didn't yield successful results either.

Answer №1

Big shoutout to Matt Pocock for sharing this insightful piece.


    function generateSchema<
      U extends Record<string, any>,
    >(input: {
      [J in keyof U]: z.Schema<U[J]>;
    }) {
      const Schema = z.object(input);
    
      return Schema;
    }

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 for integrating personalized arrow buttons into Alice-Carousel

Currently, I am in the process of creating a carousel component using alice-carousel (https://github.com/maxmarinich/react-alice-carousel/blob/master/README.md), but I am encountering some difficulties when trying to customize the arrows. The code snippet ...

Securely import TypeScript modules from file paths that are dynamically determined during execution

Imagine you have a structure of TypeScript code and assets stored at a specific URL, like between a CDN and a debug location. You want to import the main module and ensure the rest of the structure is imported correctly only when needed, without repeating ...

Looping issue with ForEach in Typscript with Firebase Functions

While browsing through various questions on this topic, I've noticed that the specific answers provided don't quite fit my situation. My query involves converting a Google Firebase RTB datasnapshot into an array of custom objects, each representi ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

Using the ternary operator will always result in a TRUE outcome

Having trouble with a ternary operator expression. AssociatedItemType.ExRatedTag ? session?.data.reloadRow(ids) : this.reloadItemRows(this.prepareItemsIdentities(ids)!), The AssociatedItemType is an enum. I've noticed that const ? 1 : 2 always retur ...

Angular routing is failing to redirect properly

After creating a sample Angular app, the goal is to be redirected to another page using the browser URL http://localhost:1800/demo. The index.html file looks like this: <!doctype html> <html lang="en"> <head> <title>Sample Ang ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

Prompt the user to take an action by opening a modal or dialogue box from a dropdown menu

I am looking to implement a functionality where a modal or dialogue will be opened when a user selects an option from a dropdown menu. As the dropdown menu will have multiple options, different dialogues/modals should appear based on the selected option. ...

What causes functions operating on mapped objects with computed keys to not correctly infer types?

If you are seeking a way to convert the keys of one object, represented as string literals, into slightly modified keys for another expected object in Typescript using template string literals, then I can help. In my version 4.9.5 implementation, I also ma ...

What is the process for exporting the reducer function and integrating it into the storeModule.forRoot within an Angular application?

Recently, I started delving into ngrx and decided to educate myself by going through the official documentation on their website ngrx.io. During this exploration, I came across a puzzling piece of code in one of their reducers. The file in question is cou ...

Accessing the Parent Variable from a Function in JavaScript: A Guide

How can you properly retrieve the value of x? let x = 5 const f = (n:number) => { let x = "Welcome"; return x * n // Referring to the first x, not the second one } Also, what is the accurate technical term for this action? ...

Exploring the capabilities of UIGrid in conjunction with TypeScript DefinitelyTyped has been a

I've noticed that the latest release of UI Grid (RC3) has undergone significant architectural changes compared to nggrid. I am encountering some problems with the definitelytyped files for nggrid because they are from a different version. Will there ...

Prevent receiving the "deprecated warning for current URL string parser" by enabling the useNewUrlParser option

I recently encountered an issue with my database wrapper class that connects to a MongoDB instance: async connect(connectionString: string): Promise<void> { this.client = await MongoClient.connect(connectionString) this.db = this.cli ...

React, Storybook - Error TS2307: Button module not found or its type declarations. Can Storybook resolve this issue?

In my React project, I have a Button component created with "create-react-app" that uses absolute paths for importing. When trying to import { Button, ButtonProps } from 'Button', I encountered an error with TS2307. The absolute path 'Butto ...

Is it possible to track when a user switches to a different component in Angular?

I'm looking to set up a confirmation popup when the user attempts to navigate to a different page. I've come across information about hostListener and canActivate, but I'm not exactly sure how to begin! Any guidance would be greatly apprecia ...

Typescript - Troubleshooting undefined error with static variables

My node API app is developed using express and typescript. The static variable of the Configuration Class is initialized with required configuration before starting the server. However, when I try to use this static variable in a separate TypeScript class ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

Enhancing data binding in Angular 2.0 with string interpolation

In my script, I am working with a string that goes like this: {name} is my name. Greeting {sender} Is there a module available in Angular 2.0 that allows me to use something similar to the string.format() function in C#? I understand that it can be achie ...

Error Encountered in Cypress: "Tried to wrap warn but it is already wrapped"

Objective: Utilize Cypress and Typescript to test for warnings and errors on the console. Error Encounter: An attempt was made to wrap warn, which is already wrapped. Snippet: describe.only("Unauthenticated User", () => { it("No C ...

What impact does setting 'pathmatch: full' in Angular have on the application?

When the 'pathmatch' is set to 'full' and I try to delete it, the app no longer loads or runs properly. import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { H ...