formik: Incorrect type inference for members of FormikErros which are elements of an array of objects
🐛 Bug report
Current Behavior
Suppose we have the following types:
interface IMember {
name: string;
}
interface IGroup {
name: string;
members: IMember[];
}
Then the type of errors.members[i]
is inferred as 'string | FormikErrors<IMember>'
which produces this error Property 'name' does not exist on type 'string | FormikErrors<IMember>'.
when one tries to access errors.members[i].name
.
Expected behavior
The type of errors.members[i]
should be 'FormikErrors<IMember>'
.
Reproducible example
Notice the error on line 57: https://codesandbox.io/s/react-typescript-uucgn
Suggested solution(s)
The solution is to delete | string | string[]
in this line.
Additional context
Your environment
Software | Version(s) |
---|---|
Formik | 2.1.3 |
React | 16.12.0 |
TypeScript | 3.8.3 |
Browser | |
npm/Yarn | |
Operating System |
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 34
- Comments: 20
@hassaans I use a ternary operator to check if there’s an error, and if there is I cast the object to the correct type. For example,
errors.memebers[i] ? (errors.members[i] as IMember).name : ''
. Fortunately, there are just a few places where I have to use this hack. Moreover, I added a comment to remind me to refactor those line when the issue is fixed in the library.Both
getIn(errors.col?.[index], 'key')
and(errors.test?.[index]) as SomeType)?.[key]
are work very well. 😉Faced it today. And yes, I thought I was going crazy with this error too. Maybe there should be added a warning to docs or something?
That worked for me.
I just ran into this problem yesterday and it was a huge pain. Why is this labeled stale?
@filip-dahlberg it’s documented https://formik.org/docs/api/fieldarray#fieldarray-validation-gotchas
Are there any chances for a better solution to this problem?
this works for me i combided @aliocharyzhkov work around
i am using formik yup and material ui
{(formik.errors.contact && formik.touched.contact) && (formik.touched.contact[i])?.number && (formik.errors.contact[i])?.number}
So glad I found this issue, I thought I was going crazy with this error. Thank you for reporting this and posting the workaround.
For
possible undefined
, optional chaining will work:errors.members?.[i] ? (errors.members[i] as IMember).name : ''
I am experiencing this error with a Object
@filip-dahlberg you use the getIn function as indicated in the documentation by @peter-visma ?
update: I tested it in a project using getIn and it solved my problem.
@imjakechapman I’ve used a temporary workaround. The issue hasn’t been resolved in the library yet, so I went ahead and created a PR. I hope it will facilitate fixing it.