I'm implementing typescript into my project for the first time and I have an error coming from onPress
which calls toggleModal
. The error is coming from onPress
According to the React Native docs, DatePickerAndroid.open() does the following:
Returns a Promise which will be invoked an object containing action, year, month (0-11), day if the user picked a date. If the user dismissed the dialog, the Promise will still be resolved with action being DatePickerAndroid.dismissedAction and all the other keys being undefined.
Can someone clarify if the error is coming from the following and how to fix it?
- The promise DatePickerAndroid.open() since it the response may or may not be returned
- Do I need to type onPress as a function with
onPress: Function
?
Error
src/DatePicker.tsx:109:25 - error TS2769: No overload matches this call.
Overload 1 of 2, '(props: Readonly<TouchableOpacityProps>): TouchableOpacity', gave the following error.
Type '(props: Props) => Promise<void>' is not assignable to type '(event: GestureResponderEvent) => void'.
Types of parameters 'props' and 'event' are incompatible.
Type 'GestureResponderEvent' is missing the following properties from type 'Props': title, onPress, onValueChange, mode
Overload 2 of 2, '(props: TouchableOpacityProps, context?: any): TouchableOpacity', gave the following error.
Type '(props: Props) => Promise<void>' is not assignable to type '(event: GestureResponderEvent) => void'.
109 <TouchableOpacity onPress={toggleModal} style={styles.fieldTextContainer}>
Types
// TypeScript: Types
interface Props {
title: string,
onPress: Function,
onValueChange: Function,
mode: 'calendar' | 'spinner' | 'default',
minDate?: Date | number;
maxDate?: Date | number;
}
interface AndroidProps {
action: 'dateSetAction' | 'dismissedAction',
newDate?: Date;
year?: number;
month?: number;
day?: number;
}
toggleModal
// Toggle Modal
const toggleModal = async (props: Props) => {
try {
// Check Platform (iOS)
if (Platform.OS === 'ios') {
// React Hook: Toggle Modal
toggle((modalVisible) => !modalVisible);
}
// Check Platform (Android)
if (Platform.OS === 'android') {
const { action, year, month, day } : AndroidProps = await DatePickerAndroid.open({
date: date,
mode: props.mode,
});
// Action: Date Set
if (
action === DatePickerAndroid.dateSetAction
&& year !== undefined
&& month !== undefined
&& day !== undefined
) {
// New Date
let newDate:Date = new Date(year, month, day);
// Select Date
selectDate(newDate);
}
// Action: Dismissed
if (action === DatePickerAndroid.dismissedAction) {
// Do Nothing
}
};
}
catch (error) {
console.log(error);
}
};
DatePicker.tsx
<TouchableOpacity onPress={toggleModal} style={styles.fieldTextContainer}>
<Text style={styles.fieldText} numberOfLines={1}>{date ? moment(date).format('MMM Do, YYYY') : 'Select'}</Text>
<Icon name="ios-arrow-forward" size={22} style={styles.arrowForward}/>
</TouchableOpacity>