Reputation: 15471
Say I have the following (trivial) flow.js example:
type Example = (d: number, b?: string) => void
const f:Example = (d: number, boo: string) => {}
This fails to compile with:
const f:Example = (d: number, boo: string) => {}
^ Cannot assign function to `f` because string [1] is incompatible with undefined [2] in the second argument.
References:
3: const f:Example = (d: number, boo: string) => {}
^ [1]
1: type Example = (d: number, b?: string) => void
^ [2]
I'm trying to understand why? I thought the second parameter (b) was annotated as optional, e.g. if it does not exist that's fine, but if it exists it has to be a string?
Clearly this is not accurate. What's the actual explanation of what's going on here? And how can I have the behavior I'm after (e.g., a function which takes either one or two arguments, and when the second argument exists it must be a string)
Upvotes: 0
Views: 59
Reputation: 51836
An optional parameter ?
means the caller may or may not provide the argument. It does not mean that a particular callee can choose whether or not to ignore the parameter.
The error is telling you that the function f
always expects a string argument even though it is not always provided, according to the Example
type.
What you probably meant to do was:
type Example = (d: number, b: string) => void
const f: Example = (d: number, boo: string) => {}
const g: Example = (d: number) => {}
This is valid because the string argument is always provided, but the callee can choose whether or not to use the argument.
Upvotes: 1