BetoIGM
BetoIGM

Reputation: 177

React Native declare interface as void for onPress call typescript error

I am trying to get rid of this typescript error from onPress call inside my TouchableOpacity component.

Called when the touch is released, but not if cancelled (e.g. by a scroll that steals the responder lock).

No overload matches this call.
  Overload 1 of 2, '(props: (TouchableOpacityProps & GenericTouchableProps) | Readonly<TouchableOpacityProps & GenericTouchableProps>): TouchableOpacity', gave the following error.
    Type 'void' is not assignable to type '(((event: GestureResponderEvent) => void) & (() => void)) | undefined'.
  Overload 2 of 2, '(props: TouchableOpacityProps & GenericTouchableProps, context: any): TouchableOpacity', gave the following error.
    Type 'void' is not assignable to type '(((event: GestureResponderEvent) => void) & (() => void)) | undefined'.ts(2769)
index.d.ts(5265, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Pick<Readonly<TouchableOpacityProps & GenericTouchableProps> & Readonly<...>, "hitSlop" | ... 36 more ... | "containerStyle"> & Partial<...> & Partial<...>'
index.d.ts(5265, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Pick<Readonly<TouchableOpacityProps & GenericTouchableProps> & Readonly<...>, "hitSlop" | ... 36 more ... | "containerStyle"> & Partial<...> & Partial<...>'

as you can see on my code below this error appers on my onPress call from my TouchableOpacity button.

  const handleChange = (id: Number) => {
    switch (id) {
      case 0:
        console.log('Se preciono el primer boton');
        break;
      default:
        console.log('default');
    }
  };

  return (
    <View style={styles.tabsContainer}>
      <TouchableOpacity style={styles.tab} onPress={handleChange(0)}>
        <Text style={styles.text}>TITULO DE PRUEBA</Text>
      </TouchableOpacity>
    </View>
  );
};

I think I just need to declare this onPress call as a void function but I can't figure how.. Does someone have any suggestion?

type error

Upvotes: 2

Views: 3194

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

Try to wrap the calling function with wrapper function () => to avoid function execution before onPress and type error.

onPress={() => handleChange(0)}

Upvotes: 7

Related Questions