Yup's Infertype feature is not compatible with optional fields

Hey there, I'm having issues with Infertype not functioning correctly for optional fields.

const userSchema = yup.object({
  name: yup.string().required(),
  age: yup.number().required().positive().integer(),
  email: yup.string().email().optional().notRequired(),
  website: yup.string().url().nullable(),
  createdOn: yup.date().default(() => new Date()),
});

The expected type should be:

/* {
  name: string;
  age: number;
  email?: string | undefined
  website?: string | null | undefined
  createdOn: Date
}*/

This is the current type being generated:

https://i.sstatic.net/mToQS.png

The email and website fields should be optional according to the schema.

Here is a snippet from my tsconfig.json file:

  "compilerOptions": {
    ...
    "strict": true,
    "strictNullChecks": true
  }

Answer №1

The latest Yup version addresses this issue by utilizing Yup.SchemaOf<Type>:

type User = {
  name: string
  age: number
  email?: string
  website?: string | null
  createdOn: Date
}


const userSchema: Yup.SchemaOf<User> = object({
  name: string().required(),
  age: number().required().positive().integer(),
  email: string().email(),
  website: string().url().nullable(),
  createdOn: date().default(() => new Date()),
});

In the next iterations of Yup, you will have access to InferType:

import { object, string, string, date, InferType } from 'yup';

const userSchema = object({
  name: string().required(),
  age: number().required().positive().integer(),
  email: string().email(),
  website: string().url().nullable(),
  createdOn: date().default(() => new Date()),
});

type User = InferType<typeof userSchema>;
/* {
  name: string;
  age: number;
  email?: string | undefined
  website?: string | null | undefined
  createdOn: Date
}*/

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

Exploring the inner workings of this JavaScript jQuery function within a snippet of code

My knowledge of JavaScript is limited, so I'm struggling to grasp the concept behind this code snippet: 1 (function () { 2 $(function () { 3 //Global ajax progress dialog box 4 //Simply run $("#ajax-progress-d ...

When there are no results, use AJAX and jQuery

What do I do if the result from my C# method is empty? jQuery.ajax({ type: "POST", url: "Me.aspx/Load", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (m ...

If a value is located, select a new value from the identical object

Is it achievable to scan through an array of JSON objects? My goal is to locate a particular value within one of the objects and then extract other values from that same object. Is this possible? Appreciate any guidance. Thank you. ...

Unique title: "Tailored confirmation dialogue box"

I am looking to customize the confirmation message using plugins. In my PHP table records, there is a delete button in each row. How can I personalize the confirmation pop-up similar to the jQuery plugin mentioned below? <?php echo' <tr class=" ...

Retrieving data from a SQL database using Node.js

As a newcomer to Node.js, I managed to fetch SQL results from my database using the code snippet below: var express = require("express"); var app = express(); var mysql = require('mysql'); app.get("/",function(req,res){ var client = mysql.c ...

Loading screen featuring animated sprites

I've recently started learning JS. I completed a few Lynda courses, but I'm struggling with creating an animated sprite preloader. I've searched extensively on Google and Stack Overflow, and although I found some helpful information, I haven ...

What is the counterpart of Python's pip freeze in Node.js?

Is there a way to generate a list of all npm modules being used along with their versions similar to Python's pip freeze? Also, is there a command in Node.js equivalent to Python's pip install -r /path/to/requirements.txt for reproducing the envi ...

Avoid commencing an EmberJs application with static assets already in place

Is there a way to obtain the minified EmberJs JavaScript and CSS assets without automatically initializing the EmberJs App? The scenario is having a login.html where users can log in, but with the static assets preloaded to eliminate waiting time once red ...

Utilizing variables to set the templateUrl in Angular2

Trying to assign a variable to the templateUrl in my component, but it's not functioning as expected. @Component({ selector: 'article', templateUrl: '{{article.html}}', styleUrls: ['styles/stylesheets/article.comp ...

Issues encountered while attempting to update data in angular2-datatable

Once the datatable has been rendered, I am facing an issue where I cannot update the data. I'm utilizing angular2-datatable. In my appcomponent.html file: If I try to update 'data2' in my appcomponent.ts file as shown below: this.httpserv ...

Angular2: Exploring the Differences Between Observable.fromEvent and Button Click

As I work with my code, I have noticed that I am using both <button (click)="callsomefucntion" /> and Observable.fromEvent<MouseEvent>(button.nativeElement.'click') interchangeably. I am curious to understand the distinction between ...

Guide to sending AJAX requests to SQL databases and updating the content on the webpage

One way I have code to showcase a user's name is by using the following snippet: <div><?php echo 'My name is ' . '<span id="output">' . $_SESSION['firstname'] . '</span>' ?></div> ...

Exploring the Logic Behind My State Store Layout - Comparing User Interface to Application State

I'm starting to get a bit confused about the difference between application state and UI state. Whenever a user picks an activity from a list on the page, an API call is triggered to retrieve the announcements for that specific activity. Is the id of ...

Retrieving outcome of Solidity contract function using web3-1.0.0-beta.27

I am using web3 1.0.0-beta.27 and the pragma solidity is set to ^0.4.2. contract Charity{ function ping() public constant returns (uint) { return 200; } } Currently, I am compiling and calling it in typescript with: import * as fs ...

Error: Module not located in Custom NPM UI Library catalog

I have recently developed an NPM package to store all of my UI components that I have created over the past few years. After uploading the package onto NPM, I encountered an issue when trying to use a button in another project. The error message "Module no ...

Step-by-step guide on converting a JSON object into a dataTable suitable for Google Visualization Chart

I'm currently facing a challenge in creating a basic chart using data from a JSON Object. Directly passing the JSON to a Line Chart is not possible, so I need to convert it into a DataTable. However, the process seems to vary depending on the structu ...

Can one provide type parameters to a generic parameter in Typescript?

Can we achieve something similar to the below in Typescript: interface Foo<X> { bar: X<string, number> } I don't believe it's possible, but Typescript's type system has proven me wrong in the past. ...

Should the button be disabled when the final color is in view?

I'm attempting to prevent the next button from being active when the last div is visible or has the class "activeNavLi". However, the code provided isn't achieving this - instead, it's removing and adding classes to different eleme ...

displaying HTML Div upon successful Ajax response in Django

I have a Django App and I would like a message to appear to the user after a successful Ajax call. Here is my Messages HTML: <a id="added" class="btn btn-template-outlined" href="{% url 'shop:add_product' id=products.id %}">Add to cart&l ...

Understanding how to infer type from the arguments of a class constructor in Typescript

Is there a way to reuse the argument type definition of a class constructor without refactoring or extracting it from the class itself? I have tried using GetProps<TBase>, but it doesn't work as expected. In the example below, the const bp defin ...