jquense / yup

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

Property 'tests' does not exist on type 'SchemaFieldDescription' #2084

Open phierru opened 1 year ago

phierru commented 1 year ago

TypeScript complains that property 'tests' does not exist on field but code runs fine.

To Reproduce

export const validationSchema = yup.object({
  firstName: yup.string().required('First name is required'),
  lastName: yup.string().required('Last name is required'),
  address: yup.string().required('Address is required'),
  zip: yup.string().required('Zip is required'),
  city: yup.string().required('City is required'),
  phone: yup.string().required('Phone is required'),
  email: yup.string().email('Invalid email address').required('Email is required'),
  picture: yup.string(),
  role: yup.string(),
  location: yup.string(),
  gender: yup.string(),
})

export const isFieldRequired = (fieldName: string): boolean => {
  const field = validationSchema.describe().fields[fieldName]
  if (!field) throw new Error(`Field '${fieldName}' not found in schema`)
  return (field.tests as Array<{ name: string }>).some((test) => test.name === 'required')
}

produces build error:

src/features/users/agents/model.ts:28:17 - error TS2339: Property 'tests' does not exist on type 'SchemaFieldDescription'. Property 'tests' does not exist on type 'SchemaRefDescription'. return (field.tests as Array<{ name: string }>).some((test) => test.name === 'required')

Expected behavior No error.

Platform typescript 5.1.6 vite 4.4.9

phierru commented 1 year ago

This works:

export const isFieldRequired = (fieldName: string): boolean => {
  const field = validationSchema.describe().fields[fieldName]
  if (!field) throw new Error(`Field '${fieldName}' not found in schema`)
  return (field as SchemaDescription).tests.some((test) => test.name === 'required')
}