marcinb1986
marcinb1986

Reputation: 892

Typescript don't allow do display error for specific input field using Formik and Yup validation

I'm using Formik for inputs and Yup as validator and I face issue with using errors to conditionally render them.

Inputs components are rendered from values using .map() method as it's originally an array of objects.

This is how i have defined inputsSchema and useFormik properties

const inputsSchema2 = Yup.object({
    luxmeds: Yup.array().of(
      Yup.object().shape({
        luxmedType: Yup.object().shape({
          package: Yup.string().required('You need to add a package'),
          type: Yup.string().required('Please add package type'),
          cost: Yup.number()
            .positive('Employee cost must be positive')
            .required('Employee cost must be added'),
        }),
        companyCost: Yup.number()
          .positive('Company cost must be positive')
          .required('Company cost must be added'),
        comment: Yup.string() || null,
        persons: Yup.array(
          Yup.object().shape({
            name: Yup.string().required('You need to provide a name'),
            lastName: Yup.string().required('You need to provide last name'),
            type: Yup.string().required('You need to provide type of person'),
          }),
        ),
      }),
    ),
  });

  const initialValues = currentEmployee.luxmeds.length
    ? currentEmployee.luxmeds
    : [emptyLuxmedData];

  const { values, handleChange, setValues, errors } = useFormik({
    initialValues: {
      luxmeds: initialValues,
    },
    onSubmit: () => undefined,
    validationSchema: inputsSchema2,
  });

When I console.log(errors) and make some wrong inputs in two elements this is how it's built enter image description here

But when I want to conditionally render component checking if specific error exist and I go lower than luxmeds[index] typescript throws me below error, LuxmedsType You can see on the right side. enter image description here

I have prepared also codesandbox where You can see exactly the problem. In sandbox it's working but not in the app. https://codesandbox.io/s/bold-butterfly-ldhbvp?file=/src/App.tsx Lines 218 & 219 and 228 & 229 are with the issue.

Can You please check what is wrong here ? I cannot figure it our.

thanks

Upvotes: 1

Views: 538

Answers (1)

Mike
Mike

Reputation: 831

FormikErrors decorates luxmeds type field to be

errors.luxmeds?: string | string[] | FormikErrors<LuxmedsType>[] | undefined

you can use type assertion to show type explicitly

{(errors?.luxmeds as FormikErrors<LuxmedsType>[])?.[index]?.luxmedType?.package && (
    <div>{(errors?.luxmeds as FormikErrors<LuxmedsType>[])?.[index]?.luxmedType?.package}</div>
    )}

Upvotes: 3

Related Questions