简体   繁体   中英

Optional parameter to function type

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, eg 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 (eg, a function which takes either one or two arguments, and when the second argument exists it must be a string)

Try flow link: https://flow.org/try/#0C4TwDgpgBAogHgQwLZgDbQLxQBQBMBcUAdgK5IBGEATgDRTkD8hAzsFQJZEDmAlFBgD4oANwD27XAChJAY1FFWUAGb54yNJhwFiZSrXqjRLNp178hAbwC+QA

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) => {}

Try it out

This is valid because the string argument is always provided, but the callee can choose whether or not to use the argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM