'ts error goes away when I use arrow function but come when I not use arrow

Why I get this error message:

Type '(message?: string | undefined) => void' is not assignable to type '(event: GestureResponderEvent) => void'.
  Types of parameters 'message' and 'event' are incompatible.
    Type 'GestureResponderEvent' is not assignable to type 'string'.ts(2322)

when I use the function like this:

  <Button onPress={handleToggleModalMessage} style={[ButtonStyles.full, s.noneBorderTop]}>
    <Text style={s.errorBtn}>Ok!</Text>
  </Button>

But when I use this above function in this way then I dont get an ts error:

  <Button onPress={() => handleToggleModalMessage()} style={[ButtonStyles.full, s.noneBorderTop]}>
    <Text style={s.errorBtn}>Ok!</Text>
  </Button>

can anyone explain me why?



Solution 1:[1]

Your first example is inferring the arguments, which means it is passing in the defaults. The first example is the equivalent of this

<Button onPress={(event) => handleToggleModalMessage(event)} style={[ButtonStyles.full, s.noneBorderTop]}>
        <Text style={s.errorBtn}>Ok!</Text>
</Button>

The type signature of handleToggleModalMessage(event) is incompatible with what you defined. It is expecting nothing or a string but you are passing in a GestureResponderEvent

Solution 2:[2]

The problem has nothing to do with react, so let me rephrase it in pure typescript:

type FN = (event: GestureResponderEvent) => void;

function handler(message?: string | undefined) {
  console.log(message);
}

const f1: FN = handler;          // ERROR
const f2: FN = () => handler();  // OK

Note that:

  • () => handler() guarantees it will ignore any arguments passed to it
  • handler can use its parameter, which is message?: string | undefined

Now consider:

const e: GestureResponderEvent = ...
f1(e);
f2(e);

Both calls are legal - both functions have type FN. If assignment of handler to type FN was legal, it would mean that we can pass an argument of type GestureResponderEvent to function accepting an optional string - which will likely break at runtime.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew
Solution 2 Lesiak