onSubmit handler typing issue
See original GitHub issueHey there 👋
I’ve been using formik
for quite some time but recently I’ve been using it with Typescript for the first time and I’ve came across some issue (I think) regarding the onSubmit
handler typing.
Because of value: object
, I’m not able to know what’s going to be the shape of my value object in TS. I’ve tried abstracting a type such as:
type FormikSubmitHandler<V> = (value: V, actions: FormikActions<V>) => void;
Although, once done that, I get a signature mismatch when I pass the function to formik. I’m not sure what’s the right fix atm but to get TS (and autocomplete) not complaining anymore I had a workaround by doing a type assertion. Here’s a complete example that illustrates the issue:
type FormikSubmitHandler<V> = (value: object, actions: FormikActions<V>) => void;
interface FormValues {
foo: string;
bar: number
}
// At this point, I don't know what's in `value` since it's type is `object`.
const myHandler: FormikSubmitHandler<FormValues> = (value, actions) => {
const typedValue = value as FormValues;
value.foo; // string
value.bar; // number
}
render() {
return <Formik onSubmit={myHandler} />
}
I’d be happy to provide a PR but I’m not sure what’s to do to get it fixed (if needs be).
Thanks.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:5 (5 by maintainers)
Top Results From Across the Web
React Typescript onSubmit type - Stack Overflow
Thanks - that helps as far as typing the e my issue is the type of the actual function. const onSubmitHandler = (e:...
Read more >How to type a React form onSubmit handler
Definitely take advantage of the type it actually is rather than just cherry-picking the values you need. The second improvement is: - function...
Read more >Forms and Events - React TypeScript Cheatsheets
If performance is not an issue (and it usually isn't!), inlining handlers is easiest as you can ... Typing onSubmit, with Uncontrolled components...
Read more >React + TypeScript: Handling form onSubmit event - Kindacode
The example below shows you how to handle the form onSubmit event in React with TypeScript. We will use the new things, including...
Read more >TypeScript: Typing form events in React - Alex Khomenko
It seems like to fix our type issue we just need to switch from event.target to event.currentTarget . const onSubmit = (event: React....
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I didn’t bother updating to TS 2.6.1, but this generic ^^ should do the trick.
Cool, that should do it 😃 — Thanks!