Recently, I embarked on a project using React Native with Typescript and encountered Formik as my chosen tool for building forms within the application.
I found the informative tutorial guide by Formik to be very helpful, especially the section on using Formik with React Native in JavaScript.
However, when attempting to convert this example to typescript, I encountered a typing error related to the Button's onPress attribute
:
No overload matches this call.
Overload 1 of 2, '(props: Readonly<ButtonProps>): Button', gave the following error.
Type '(e?: FormEvent<HTMLFormElement>) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.
Types of parameters 'e' and 'ev' are incompatible.
Type 'NativeSyntheticEvent<NativeTouchEvent>' is not assignable to type 'FormEvent<HTMLFormElement>'.
Types of property 'nativeEvent' are incompatible.
Type 'NativeTouchEvent' is missing properties such as bubbles, cancelBubble, cancelable, composed, and more.
Overload 2 of 2, '(props: ButtonProps, context?: any): Button', gave the following error.
Type '(e?: FormEvent<HTMLFormElement>) => void' is not assignable to type '(ev: NativeSyntheticEvent<NativeTouchEvent>) => void'.ts(2769)
index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Button> & Readonly<ButtonProps> & Readonly<{ children?: ReactNode; }>'
index.d.ts(6926, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAt...
After some investigation, it appears that the handleSubmit
function
(e?: FormEvent<HTMLFormElement>) => void
, expects an event from a form submission (similar to the onSubmit
attribute of a HTML form
). Since React Native does not have a direct equivalent to a traditional form, it's raising an issue when receiving the input type (ev: NativeSyntheticEvent<NativeTouchEvent>) => void
for the RN Button's onPress
attribute.
To work around this error temporarily, I used the following approach, although I'm not entirely satisfied:
<Button
title="Do it !"
color={colors.red}
onPress={
(handleSubmit as unknown) as (
ev: NativeSyntheticEvent<NativeTouchEvent>
) => void
}
/>
I am seeking advice on how to correctly resolve this typing error. Any guidance would be greatly appreciated!
Thank you for your assistance.