Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is InferType for nullable().required() schema correct? #2253

Open
krisko4 opened this issue Oct 28, 2024 · 0 comments
Open

Is InferType for nullable().required() schema correct? #2253

krisko4 opened this issue Oct 28, 2024 · 0 comments

Comments

@krisko4
Copy link

krisko4 commented Oct 28, 2024

Hello, let's consider a simple example:

const validationSchema = object({
  test: string().nullable().required()
})

type FormData = InferType<typeof validationSchema>;

const DEFAULT_VALUES : FormData = {
  test: null
}

For the example mentioned above, TypeScript error appears:

Type 'null' is not assignable to type 'string'

But in practice, everything works fine. The initial value of "test" property is null and when the form is submitted, yup validates that null is not a correct value. So from TypeScript perspective, the inital value of "test" can be null.

I don't understand why required() type definitions mark the returned type as NonNullable. I've browsed a lot and I found out that there was a discussion about this issue in the past:

DefinitelyTyped/DefinitelyTyped#41789

The conclusion was that nullable().required() should infer type as T | null. Why has it not been applied in the recent yup versions? If this is not a bug, what is a workaround to make the case presented in the example type-safe? Thanks in advance.

P.S. I'm not looking for "set you initial value as an empty string" advice. This is just a simple example. In real case scenario, test is an object which can be retrieved as a null from the server.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant