Indeed, the Typescript Schema Interface for `Yup.lazy()` is essential for creating dynamic validation schemas

I am currently facing a challenge in creating a TypeScript interface for a Yup schema (https://github.com/jquense/yup/blob/master/docs/typescript.md)

Here is the TypeScript interface I am working with:

interface TestInterface {
  name: string;
};

The following return type is acceptable:

const testSchema: Yup.SchemaOf<TestInterface> = Yup.object().shape({
  name: Yup.string().required()
});

However, in my code I am using Yup.lazy(), and I am unsure how to create an interface for the following scenario:

const testSchema: Yup.SchemaOf<TestInterface> = Yup.object().shape({
  name: Yup.lazy(() => Yup.string().required())
});

The error message I am encountering is:

Type 'ObjectSchema<Assign<ObjectShape, { name: Lazy<RequiredStringSchema<string, Record<string, any>>, Record<string, any>>; }>, Record<...>, TypeOfShape<...>, AssertsShape<...>>' is not assignable to type 'ObjectSchemaOf<TestInterface>'.
  Type 'Assign<ObjectShape, { name: Lazy<RequiredStringSchema<string, Record<string, any>>, Record<string, any>>; }>' is not assignable to type '{ name: BaseSchema<string, AnyObject, string>; }'.
    Types of property 'name' are incompatible.
      Type 'Lazy<RequiredStringSchema<string, Record<string, any>>, Record<string, any>>' is missing the following properties from type 'BaseSchema<string, AnyObject, string>': deps, tests, transforms, conditions, and 35 more.ts(2322)

Answer №1

Your demo is functioning as intended when utilizing Yup.ObjectSchema, but it's crucial to enforce the presence of your object.

Make sure to append .required() to your .shape or .object chain to ensure that TypeScript recognizes the existence of your schema fields. This essentially acts as NonNullable<TestInterface>

//    ✅ successful type
const testSchema1: Yup.ObjectSchema<TestInterface> = Yup.object().shape({
  name: Yup.string().required(),
}).required();

//    ✅ successful type
const testSchema2: Yup.ObjectSchema<TestInterface> = Yup.object().shape({
  name: Yup.lazy(() => Yup.string().required())
}).required();

Note: Tested with version 0.32.11 at the time of this post. A runkit example in plain JS with placeholders for types can be accessed [here]

Source: https://github.com/jquense/yup/#ensuring-a-schema-matches-an-existing-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

Reactivity in Angular Autocomplete with API Integration

I went through all the tutorials on Angular Autocomplete using API to follow the steps. I implemented valueChanges to monitor the form control, used switchMap to send a new request with each keyword change, and then displayed the data in the autocomplete d ...

Frozen objects in Typescript 2 behave in a variety of ways depending on their shape

Let's say I'm working with an object whose inner structure is unknown to me because I didn't create it. For instance, I have a reference to an object called attributes that contains HTML attributes. I then made a shallow copy of it and froze ...

Using Typescript to extract elements from one array and create a new array

I have a set of elements "inputData" , and it appears as follows : [{code:"11" , name= "test1" , state:"active" , flag:"stat"}, {code:"145" , name= "test2" , state:"inactive" , flag:"pass"}, {code1:"785" , name= "test3" , state:"active" , flag:"stat"}, .. ...

Angular2 Error: Cannot have two identifiers with the same name, 'PropertyKey' is duplicated

I am currently developing an application with angular2 using angular-cli. Unfortunately, angular-in-memory-web-api was not included by default. After some research, I manually added the line "angular-in-memory-web-api": "~0.1.5" to my ...

The loading template remains visible despite the Eventsource being closed when using the Async Pipe

How can I resolve the issue I'm facing with the Angular async pipe and event source while using Spring boot WebFlux? I need to display a "loading data" message until the API call is complete. Once the API fetches data, I want to show the retrieved dat ...

Comparing two arrays in Angular through filtering

I have two arrays and I am trying to display only the data that matches with the first array. For example: The first array looks like this: ["1", "2" , "3"] The second array is as follows: [{"name": "xyz", "id": "1"},{"name":"abc", "id": "3"}, ,{"name ...

What is preventing me from utilizing TouchEvent in Safari browser?

Recently, while working on a project utilizing Angular 8, I encountered an issue regarding touch event handling. In my code, I had a handler setup like this: @HostListener('touchend', ['$event']) onTouchend(event: TouchEvent) { eve ...

Issue with React component not updating when the "Date" value in its state is changed

Disclaimer: I am currently working with React using Typescript. I have a particular component that, upon mounting, initializes state with a date like this: constructor(props: SomeProps) { super(props); const fromDate = new Date(); fromDat ...

Issue with debounce function failure in handling onChange event for a controlled input field

Currently, I am experimenting with the Material UI React framework. I recently moved my application to Material UI using TypeScript. However, I seem to be encountering an issue with the debounce function when used in the onChange handler for input fields. ...

The inclusion of a custom list preview with prepare in the sanity schema results in errors during the construction

I recently started working with next.js, TypeScript, and Sanity, and everything has been going smoothly so far. I have multiple schemas defined in my project and it works fine in development. The linting checks also do not show any errors. However, when I ...

Compilation error occurred when running Angular with mat-form: ngcc encountered an issue while processing [email protected]

Currently dealing with a compile error in a small mat-form example that I created. Unfortunately, I am unable to pinpoint the exact issue causing this error. If you have a moment, please take a look at the code here: https://stackblitz.com/edit/angular-iv ...

Handlebar files are not compatible with Typescript loading capabilities

I am encountering an issue with my directory structure as follows : src |- server |- myServer.ts |- views |- myView.hbs dist |- server |- myServer.js The problem lies in the fact that the dist folder does not have a views subfolder, where the J ...

Is it possible to apply filters to individual columns in a dynamic mat table using Angular?

Does anyone know how to add a filter for each dynamic column in an Angular Material table? I've only found solutions for static headers, but my table headers are constantly changing. I'm looking for something similar to this example: https://i.st ...

How to Create a Dependency on Tabs for Selecting Items in an Angular 7 Materials Dropdown List

I am currently working with angular 7 in combination with angular materials. In my project, I have implemented a tab as well as a selection list. What I aim to achieve is that the items displayed in the selection list are dependent on the chosen tab in th ...

Whenever I attempt to host my Node.js app using the GCP deploy command, it fails to work properly. The error message that appears states: "Module 'express' cannot be found."

My NodeJS application is written in TypeScript and utilizes the Express framework. I'm looking to host it on the GCP cloud using the gcloud app deploy command. First, I compile my TS sources to JavaScript - is this the correct approach? Afterwards, I ...

Show a few values as a string in Angular using Typescript

I am working with JSON data and I want to know how to display hobbies without including the word "all" in an Angular/TypeScript application. { "Name": "Mustermann1", "Vorname": "Max1", "maennlich& ...

Is there a way for one function to access the validation of a nullable field performed by another function?

Below is a TypeScript code snippet. The function isDataAvailable will return true if the variable data is not undefined. However, an error occurs in the updateData function when trying to access data.i++: 'data' is possibly 'undefined'. ...

Unable to retrieve base64 pdf file due to network connectivity problem

I am trying to download a base64 pdf file from local storage using vue3 typescript. Here is the code snippet I'm using: downloadPDF() { const linkSource = `data:application/pdf;base64,${'json.base64'}`; const downloadLink = ...

Contrary to GraphQLNonNull

I am currently working on implementing GraphQL and I have encountered a problem. Here is an example of the code I wrote for GraphQL: export const menuItemDataType = new GraphQL.GraphQLObjectType({ name: 'MenuItemData', fields: () => ...

Filling a data entry with simultaneous commitments

Sample code: type Alphabet = 'a' | 'b' | 'c'; const alphabetMap: Record<Alphabet, null> = { 'a': null, 'b': null, 'c': null} // Select any asynchronous processing function you prefer funct ...