The following code does not throw any errors.
function add(a: number, b: number) {
return a + b;
}
var c: number = add(1, 2, 3);
There are hacky ways to fix this problem but I don't see why we should be so liberal as to allow this now that rest params exist.
The recommended solution is
function add(a: number, b: number, _: void) {
return a + b;
}
This is probably still hacky, but also more reasonable than the fix you linked to.
More generally, yeah we might revisit this design decision in the future. We definitely need it for function-function matching, because it's usual in JS to define closures that don't mention unnecessary params and pass them to places that expect closures with all params (e.g., https://github.com/facebook/flow/blob/master/lib/core.js#L201).
The recommended solution doesn't fix the problem though, add(1, 2, undefined, 3) is still possible
What is the problem, though? Passing extra arguments isn't a runtime error; why should it be a static error?
@samwgoldman indeed, IMO the current Flow behaviour is correct, describes how actually JavaScript works (was just pointing out that the proposed solution was not a real fix if you want to enforce the arity)
Sure, it's not a runtime error, but suppose the arity of a function changes such that it no longer accepts an extra argument for whatever reason. That wouldn't be an error with the current behavior.
Is there a good reason to keep the current behavior if we have a chance to be more strict and catch potential bugs? Given how simple rest arguments are to use now, I seems it would actually be okay to do so.
it's
function add(a: number, b: number, ...rest: Array<void>) {
return a + b;
}
@alexeygolev has probably the best solution to this for now if you are concerned about adding arguments in the future and it being used incorrectly today. This is not unlike adding additional properties to objects than is in the type definition (although we did just add Exact for that).
@thejameskyle maybe it worth adding syntactic sugar to make this easier?
Maybe should be added to a more stringent checks? Something as strict mode in javascript.
...rest: Array<void> should be Flow's default behavior. https://github.com/facebook/flow/issues/1017#issuecomment-273694538
Duplicate of https://github.com/facebook/flow/issues/1017
Glad to see this decision has been reversed!
Most helpful comment
Glad to see this decision has been reversed!