facebook / facebook/flow

Support optional parameters in the middle of the parameter list

Open
#433 0 comments 2 reactions 0 assignees View on GitHub
wishlist
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

This pattern comes up in external libraries, and has been an issue before in the type declarations for node libraries (#333).

Although @gabelevi made it clear there is ambiguity here, it feels like we should be able to support any common case. Take the following example:

```
declare function readFile(
filename: string,
options?: Object | string,
callback: (err: ?Error, data: Buffer) => void
): void;
```

(Omitting the callback does lead to an exception at runtime, so marking the callback as optional isn't very satisfying.)

The [implementation of readFile in node](https://github.com/joyent/node/blob/4d9c81b7e2522c5d5d9d35058cbb0bce1228d360/lib/fs.js#L246) shows how the runtime type checking works. This to me is similar to flow's own refinements.

I think we could consider the above definition of `readFile` to be a short-hand notation for a set of overloaded declarations:

```
declare function readFile(
filename: string,
options: Object | string,
callback: (err: ?Error, data: Buffer) => void
): void;
declare function readFile(
filename: string,
callback: (err: ?Error, data: Buffer) => void
): void;
```

Flow would then use the arity of the call site to disambiguate between the two overrides. In other cases, we should be able to use types to disambiguate.

Yes, there will be ambiguous cases, and flow should complain in those situations. If something is ambiguous in flow, it's probably ambiguous to the runtime as well. I don't think we will find ambiguous cases in the APIs we want to declare, but we seem to run into unambiguous cases a lot!

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.