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?
CodePudding user response:
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
CodePudding user response:
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 ithandler
can use its parameter, which ismessage?: 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.