Nisha Patel
Problem
I have a form that can create or edit an object. Each attribute is required so you cannot create/save an object without a valid A and B. I'm using yup and TypeScript latest version.
To do that I have two number inputs that can return a number or NaN if empty or invalid number. I made a validation function that I can then add to yup with addMethod :
I need to convert Nan value to undefined to avoid an exception on min/max. This function work as intended despite the type error :
My problem is that I don't want to change the base type to number | undefined because unless I'm not in the form A and B cannot be undefined. I thought about using two different types (Exemple and ExempleForm) but that would duplicate all the types used in forms in my application.
I'm looking for a way to write a validation function that does the same thing, with this type and without the error.
Is there a solution to what I'm asking?
Solution
You can try like this :
As you can see here, you can use nullable method in Yup instead of undefined.
Suggested blogs:
>Why Typescript does not allow a union type in an array?
>Narrow SomeType vs SomeType[]
>Create a function that convert a dynamic Json to a formula in Typescript
>How to destroy a custom object within the use Effect hook in TypeScript?
>How to type the values of an object into a spreadsheet in TypeScript?
>Type key of record in a self-referential manner in TypeScript?
>How to get the last cell with data for a given column in TypeScript?
>Ignore requests by interceptors based on request content in TypeScript?
>Create data with Typescript Sequelize model without passing in an id?
>How to delete duplicate names from Array in Typescript?