Using declare we can overload methods in classes:
declare class Foo {
bar(a: number, b: string): number;
bar(b: string): number;
}
But is it possible without declare?
Here is a not working example just to illustrate what I mean:
class Foo {
bar(a: number, b: string): number;
bar(b: string): number;
bar(aOrB, maybeB) {
return maybeB !== undefined ? maybeB : aOrB;
}
}
See intersection types example:
/* @flow */
class Foo {}
class Bar {}
declare var f: ((x: Foo) => void) & ((x: Bar) => void);
f(new Foo());
f(new Bar());
f(true); // Flow will error here.
It should work outside of declarations too.
Right. But how do I use this inside class {}?
Just to clarify: you've made function f overloaded, but I need to make a class method overloaded.
@rpominov ah... right, not sure how it fits with method types declarations. But the case you described can be typed with:
class Foo {
bar(aOrB: number | string, maybeB?: string): number {
return maybeB !== undefined ? maybeB : aOrB;
}
}
right?
@rpominov disregard my last response, you have a dependency between args. Waiting for some smarter one to answer that then.
Not quite same thing.
In your version bar(1) is allowed, while with proper overloading if second argument not provided first one must be a string.
But anyway, this is not my real case. I need this for a static method similar to Promise.all().
I don't think it's possible. The easiest way around is to have a separate declaration and cast implementation to declaration type via any.
That is an option. But will I have to duplicate all other methods in declaration and in implementation then?
But will I have to duplicate all other methods in declaration and in implementation then?
Yes, I think that's the only option without affecting runtime behaviour
Seems like a room for improvement for Flow then. There should be a way to do this somehow without duplication.
The problem is, it's hard to check for Flow that a method body satisfies multiple signatures. Which is why we implemented it for declare class first, since they have no method bodies. :P
This should be fixed.
Most helpful comment
The problem is, it's hard to check for Flow that a method body satisfies multiple signatures. Which is why we implemented it for
declare classfirst, since they have no method bodies. :PThis should be fixed.