jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

InferTypes of object are always possibly undefined #2079

Closed terragady closed 1 year ago

terragady commented 1 year ago

When using InferType on yup schema which are objects, every key is possibly undefined Best way to describe it is:

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()),
}).required();

type types = InferType<typeof userSchema>

and this gives:

type types = {
    age?: number;
    name?: string;
    email?: string;
    website?: string;
    createdOn?: Date;
}

I want to use it with connection to React Hook Form in yupResolver

  const methods = useForm<types>({
    resolver: yupResolver(userSchema),
  });

and then this gives an error of incompatible types - of course.

Why yup InferType always adds undefined even if field is required?

https://codesandbox.io/s/kind-sammet-8yrjjf?file=/src/App.tsx

I have narrowed it down to version 1.0.0-alpha0 shows everything as defined even the optional not required ones and everything above that version shows always as optionally undefined

jquense commented 1 year ago

Do you have the strictNull TS config option set?

terragady commented 1 year ago

Ah yes sorry it was commented out in my tsconfig, looks like this solve the issue