The ValidationSchema Type in ObjectSchema Seems to Be Failing

  • yup 0.30.0
  • @types/yup 0.29.14

Struggling to create a reusable type definition for a Yup validationSchema with ObjectSchema resulting in an error.

Attempting to follow an example from the Yup documentation provided at: https://github.com/jquense/yup#ensuring-a-schema-matches-an-existing-type

interface TestValidationSchema {
  title: string;
}

const validationSchema: Yup.ObjectSchema<TestValidationSchema> = Yup.object({
  title: Yup.string().required()
});

...

 return (
    <Formik
      initialValues={initialValues}
      onSubmit={handleSubmit}
      validationSchema={validationSchema}
    >
...

Encountering this error:

Type 'ObjectSchema<Shape<object | undefined, { title: string; }>, object>' is not assignable to type 'ObjectSchema<TestValidationSchema, object>'.
  Types of property 'fields' are incompatible.
    Type '{ title: Schema<string, object>; } | undefined' is not assignable to type '{ title: Schema<string, object>; }'.
      Type 'undefined' is not assignable to type '{ title: Schema<string, object>; }'.

Updated to version 32.11 of Yup and encountered a different but still puzzling error related to incorrect usage of ObjectSchema.

Type 'OptionalObjectSchema<{ title: RequiredStringSchema<string | undefined, AnyObject>; }, AnyObject, TypeOfShape<{ title: RequiredStringSchema<string | undefined, AnyObject>; }>>' is not assignable to type 'ObjectSchema<TestValidationSchema, AnyObject, TypeOfShape<TestValidationSchema>, AssertsShape<TestValidationSchema>>'.
  The types of 'fields.title' are incompatible between these types.
    Type 'RequiredStringSchema<string | undefined, AnyObject>' is not assignable to type 'string'.ts(2322)

Seeking assistance on resolving this issue.

UPDATE

Upon inspecting the type returned from the above validationSchema, I found that the following type works. Still curious as to why the Yup documentation example isn't functioning correctly for me:

type ValidationSchema = Yup.ObjectSchema<{
  title: string;
} | undefined, object>

Answer №1

Ensure you update both yup and @types/yup to the latest versions: @types/yup 0.29.14 yup 0.32.11 This should resolve any issues you are experiencing.

Answer №2

It's crucial to note that null and undefined are not permitted when using the 'Required' rule, especially when applying it to the title.

The issue may actually lie with Yup.object(...), which currently allows for undefined. Consider also making this field required by using required().

To learn more about utilizing Yup.object(), visit: https://github.com/jquense/yup#object

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

While utilizing Ionic to upload images to a server, I encountered the FileTransferError error code 3

I have successfully uploaded an image from the gallery, but I am facing issues while uploading multiple images at once. Here is the code snippet I am using: pictureUpload(x){ // x represents the file path like - file:///storage/emulated/0/Download/palak ...

The object 'key' is not a valid property of the type 'Event'

Recently, I decided to delve into Tauri using vanilla Typescript code. Oddly enough, when working in vscode, it flagged event.key and foo_input.value as not properties of Event. However, when running the Tauri application, everything worked perfectly fine ...

Navigating with Angular 6 using routerlink in a child module with router-outlet specified in the parent component (app.component

I'm currently working with the RouterModule and encountering an issue with the routerLinks. The problem I am facing is that the routerLinks are not functioning properly (the anchor tags are not clickable). This issue arises because they are located w ...

Difficulty in converting class-based JS useState array to TypeScript Hook

Recently, I've delved into the world of React / TypeScript and have taken on a personal project to enhance my skills. As part of this project, I am in the process of transitioning some class-based code into hooks. Here is the (JS) class-based code th ...

Inject props into a Component nested within a Higher-Order-Component (HOC)

In attempting to grasp the concept of creating a React Higher Order Component from this particular article, I find myself struggling to fully understand and utilize this HOC. interface PopupOnHoverPropType { hoverDisplay: string; } const WithPopupOnHov ...

Adding custom CSS and JavaScript to an Angular 4 project can be done by including the necessary

When working with Angular 2, I was able to include stylesheets directly in the index.html like so: <link rel="stylesheet" href="css/mycss.css"> However, with Angular 4, the styles need to be added to the angular-cli.json file within the styles and ...

Tips for patiently anticipating the completed response within an interceptor

Using the interceptor, I want to display a loading spinner while waiting for subscriptions to complete. This approach works well in individual components by showing and hiding the spinner accordingly: ngOnInit() { this.spinnerService.show(); this. ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Dealing with Dependency Injection Problem in Angular 6

I am grappling with a challenge in my cross-platform Angular application. The crux of the issue is determining the platform on which the app is running and accordingly injecting services. Below is how I've structured it: @NgModule({ providers: [ ...

When using Angular, a service can be declared in the viewProviders of the parent component and then accessed in the viewProviders of the child

Imagine a scenario where there is a parent component called AppComponent, a directive named MyDirective, and a service named SimpleService. In this case, MyDirective is utilized in the template of AppComponent and injects SimpleService using the Host deco ...

Angular background image not displayed

After searching extensively, I came across many examples that didn't work for me. I'm not sure what I'm doing wrong and I need assistance! I noticed that I can see the image if I use the <img> tag, but not when I try to set it as a ba ...

Is there a way to trigger the click event in the week view of an Angular 2+ calendar?

https://i.sstatic.net/Vx2x8.png HTML Templates <mwl-calendar-week-view [viewDate]="viewDate" [refresh]="refresh" (click)="weekDayClick($event)"> </mwl-calendar-week-view> In the component file weekDayCl ...

Do you believe this problem with transpilation has been properly reported to babel-jest?

I recently encountered a problem in the jest project regarding babel-jest transpilation. I added some code that appeared to be error-free, but caused transpilation to fail completely. Although the issue seemed related to a Typescript Next project, there a ...

Encountering errors in Angular when trying to access a property that is undefined using

One of the components I've created is being used in its parent component: <app-event-menu-nav [event]="event"></app-event-menu-nav> Below is the code for this component: import {Component, OnInit, ChangeDetectionStrategy, Input} ...

Typescript - unexpected behavior when using imported JavaScript types:

I am struggling with headaches trying to integrate an automatically generated JavaScript library into TypeScript... I have packaged the JavaScript library and d.ts file into an npm package, installed the npm package, and the typings modules in the TypeScr ...

Displaying a div component in React and Typescript upon clicking an element

I've been working on a to-do list project using React and TypeScript. In order to display my completed tasks, I have added a "done" button to the DOM that triggers a function when clicked. Initially, I attempted to use a useState hook in the function ...

The type 'number' cannot be assigned to the type 'Element'

Currently, I am developing a custom hook called useArray in React with TypeScript. This hook handles array methods such as push, update, remove, etc. It works perfectly fine in JavaScript, but encounters errors in TypeScript. Below is the snippet of code f ...

"Creating a visual representation of models exchanged between the client and server through Rest

Currently, I am working on a project that involves client-server communication via rest API, with Angular 2 calling restful web services as the primary method. The client side is written in Typescript, which is a subset of JavaScript. My main challenge li ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

Encountering a bug in Angular 10 while attempting to assign a value from

I am having trouble updating the role of a user. In my database, I have a user table and a role table with a ManyToMany relation. I can retrieve all the values and even the correct selected value, but I am encountering issues when trying to update it. Her ...