-
Notifications
You must be signed in to change notification settings - Fork 1.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Function overload best practices #4305
Comments
I think you want an intersection type here: a value of type F can be used both as a function of the first type and as a function of the second type; it isn't one or the other. (Easy mistake to make when you're thinking about the function's definition, since you have to flip your ands and ors inside the function body: if the function is a |
@rhendric thanks for the tip about Looks like for now Flow is working OK (and checks proper types) when intersection is in use. Flow also allows direct function overload (in similar to TS manner) inside declaration files, by putting multiple function declarations of the same function name. |
You can use function overloading inside non-declaration files like this: declare function first_number(x: string, ...args: number[]) => number;
declare function first_number(...args: number[]) => number;
function first_number (...args) {
if (typeof args[0] === 'boolean')
{
return args[1]
}
else
{
return args[0]
}
} |
@oriSomething Why does this report no errors? |
There is no "official" support for that. The non "declared" function treat is as var x: string = first_number(1); // Will emit error |
Interfaces seem to have the behaviour you're looking for: #3021 (comment). |
I'm often stagger against need to describe in Flow functions which can be invoked with several different arguments' typesets. This is a common practice for JS to allow functions to work flexible depending on argument types.
Consider the following example:
I need to describe a function which accepts optional argument in first position. Something like a flag:
When you put your optional flag argument on the first place it makes flag more clear to read and less miss-prone. The package extend uses this manner for its
deep
flag.So, my synthetic example for such case:
Then the function which implement this can be the following:
The flag is ignored, but it don't make the idea less clear.
I'm using union (and not intersection) and expecting this definition to work OK. However I got the error:
just if I was using intersection.
This is not the first time I'm struggling with describing polymorphic/variadic functions in Flow. This whole part of the typesystem is obscure for me. Will glad for any tips and help.
The text was updated successfully, but these errors were encountered: