The return type of object.keysof() is lacking in typing

Currently, I'm in the process of developing a function that takes a zod object as input and produces a zod enum using the keyof() function.

This is what I have so far:

const FormSchema = z.object({
  username: z.string().trim().min(1).max(20),
  password: z.string().trim().min(12).max(100),
  rememberMe: z.coerce.boolean().optional().default(false),
  redirectTo: z.string().trim().startsWith("/"),
});

type Schema<T extends z.AnyZodObject> = z.infer<T>
type SchemaEnum<T extends z.AnyZodObject> = ReturnType<T["keyof"]>;

function getEnumFromSchema<T extends z.AnyZodObject> (schema: T): SchemaEnum<T> {
  const shape = schema._type;
  return shape.keyof();
}

function test () {
  const t = getEnumFromSchema(FormSchema);
}

On codesandbox, when I hover over t, it displays

const t: z.ZodEnum<["username", "password", "rememberMe", "redirectTo"]> 
Although this returns an enum, TypeScript throws the error
Type 'ZodEnum<never>' is not assignable to type 'ReturnType<T["keyof"]>'.

I've been trying to troubleshoot this issue, but something feels off to me, and I haven't been able to pinpoint where I might be going wrong.

Answer №1

After experimenting with a solution provided by TheEnigmaticMind, I discovered that following this approach leads to accurate inferences.

Unlike the previous example which failed to convert literals to a union, this updated code successfully infers type keys and outputs an enum.

function generateEnumFromSchema<S extends z.ZodRawShape>(schema: z.ZodObject<S>) {
  return schema.keyof();
}

function runTest() {
  const result = generateEnumFromSchema(FormStructure);
  // The variable 'result' is inferred as `z.ZodEnum<"username" | "password" | "rememberMe" | "redirectTo">`
}

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

Transferring a Dictionary Key to a JavaScript function

I need help with sending a Dictionary key (which is a string) to a JavaScript function. <% foreach (var field in Model.Fields) { %> <tr><td> <a href="#" onclick="javascript:EditField(<%= field.Key %>)"> ...

basic file not functioning properly

So I am currently developing a straightforward script to assign the value " ...php?answer=1" only if the java is enabled. It so happens that I have made some progress on this... <script language="text/javascript"> document.form.answer.value=1; < ...

Troubleshooting an issue with an AJAX request

Having trouble getting the HTML back from an AJAX call - works in FF but returns "null" in IE when using alert(result.html()); Here's the code, any suggestions? Thanks! The errors variable is also null in IE. It doesn't matter what element I u ...

Creating dynamic form calculations using Javascript, Ajax, and JQuery on user input change

My form needs to be populated from a MySQL database and human input. The goal is to calculate 2 additional fields based on the existing ones. Example Form: Indicator (MySQL) (dropdown) Hour Equivalent (MySQL) SKS Equivalent (MySQL) Amount (User) Hour To ...

Is there a way to ensure that my mouseenter function does not run when it is currently in the process of running?

Issue at hand: Currently, I am tackling a problem with the mouseenter function $('.filmstrip').bind('mouseenter',function(){ var isRunning = false; var $elem = $(this), width = $elem.width(), ...

Converting input/select string values into strongly-typed values with Angular 2

I've been searching for a solution for quite some time now, but I'm still a bit confused. The issue is simple: I have a model with a boolean property that I'm mapping to a select element in Angular. The select allows the user to choose betwe ...

Creating a Dynamic Dependent Dropdown with Jquery and Ajax in PHP

As a newbie in coding, I stumbled upon some valuable information to enhance my register form using Ajax. While the PHP files seem to be functioning correctly, I suspect that the JS file is not performing as expected. In the register form, you'll find ...

The amount of child elements in Three.js

After creating a three js object and adding some children to it, I changed the length of children to 0. As a result, the objects went out of screen. But will this action completely remove the objects from both the screen and memory? var balls = new THREE. ...

What are some ways that we can enhance each other's value?

I am currently delving into the realm of Java-script, with the goal of creating an input field for numbers. My vision is to have a scenario where when a user enters a number in the input field, my script will display it in a paragraph or another text field ...

What is the method for passing parameters to a generic Express middleware function specific to each route?

I've created a versatile validation function that accepts an object as its main parameter, with a key called required (and others) that holds an array of strings. This function is designed to check incoming front-end data against any keys listed in th ...

How can you generate a distinct id value for each element within an ngFor iteration in Angular 4?

I encountered an issue where I must assign a distinct id value to each data row within my *ngFor loop in angular 4. Here is the code snippet: <div *ngFor="let row of myDataList"> <div id="thisNeedsToBeUnique">{{ row.myValue }}</div> & ...

How can I alter the background color while performing a transformation in JS/CSS?

I'm currently working on achieving a flipboard effect for some divs, where one side is white and the other is black. Here's what I have so far: setInterval(function () { document.getElementById('test').classList.toggle('flipped& ...

Having trouble dynamically assigning the ng-model attribute

I am trying to populate the ArrayINeed array, which is the object I need to pass back to the API call. Currently, I am getting undefined for "ConfirmedTrackingReferenceNumbers": Dc.ArrayINeed. Despite researching various posts online and on SO, I have been ...

Problem with file organizer in Angular application - unable to see files and directories

I successfully integrated a file manager component following this tutorial. Despite no errors in vscode or chrome debug tool, my folders are not visible. Can anyone help me troubleshoot this issue? https://i.stack.imgur.com/ihEak.png I am unsure how to r ...

Is there a way to transform a callback into promises using async/await, and convert a prototype function into a standard

I need help converting a code callback function to promises. When attempting to convert the prototype to a normal function, I encounter an error that I can't fix on my own. I am eager to utilize the ES7 async-await feature to avoid callbacks. functio ...

Looking for assistance in showcasing information retrieved from an external API

I've been working with an API and managed to fetch some data successfully. However, I'm having trouble displaying the data properly in my project. Can anyone provide assistance? Below is a screenshot of the fetched data from the console along wit ...

File manager built with React, allowing users to easily remove files stored in the browser or on a local host

I am in the process of developing a reactjs based web application for file management on my local machine. Currently, I am utilizing code from a project located at https://github.com/knyzorg/simple-file-explorer which employs WebSockets to display files. M ...

What is the best way to transfer data to the child component?

Whenever a product is selected, the corresponding list of colors in the AutoComplete for color filtering should only display variations where the quantity is greater than 0. For instance, selecting the product Tumbler should show Black, Pink, and Green as ...

Is there a way to determine if the current path in React Router Dom v6 matches a specific pattern?

I have the following paths: export const ACCOUNT_PORTAL_PATHS = [ 'home/*', 'my-care/*', 'chats/*', 'profile/*', 'programs/*', 'completion/*', ] If the cur ...

Tips for organizing checkboxes in rows horizontally

My question is related to this issue I am trying to arrange my checkboxes in 4 columns horizontally <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> ...