I’m trying to build a form in my React Native application with Typescript using Formik, following the tutorial guide and the Formik with RN section in JS.
When I tried to translate the example into typescript, I got the following typing error on 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 the following properties from type 'Event': bubbles, cancelBubble, cancelable, composed, and 17 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...
I understand that the handleSubmit
function (e?: FormEvent<HTMLFormElement>) => void
expects an event from a form submission (onSubmit
attribute of a form
element). Since there is no Form equivalent in RN, it complains about receiving the (ev: NativeSyntheticEvent<NativeTouchEvent>) => void
from the RN Button's onPress
attribute.
To get rid of the error, I used this workaround:
<Button
title="Do it !"
color={colors.red}
onPress={
(handleSubmit as unknown) as (
ev: NativeSyntheticEvent<NativeTouchEvent>
) => void
}
/>
I’m not satisfied with this solution and would like to know how to solve this typing error properly.
Can you help me?