-
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
Is it possible to restrict type of this
for a particular method?
#1369
Comments
I don't know if you could do this in your project, however I think you should use inheritance here, like: /* @flow */
class Foo<T> {
_x: T;
constructor(x: T) {
this._x = x;
}
getX(): T {
return this._x;
}
}
class FooBar extends Foo<number> {
constructor(x: number) {
super(x);
}
getXMultBy(y: number) {
return this._x * y;
}
}
(new Foo('bar')).getX(); // ok
(new FooBar(12)).getXMultBy(10); // ok
(new Foo(12)).getXMultBy(10); // error! If this is not feasible, you could try using invariant |
@leonardfactory Yeah, inheritance isn't very convenient in my case. Invariant also will work, but only at run time... Some context: in Fantasy Land some methods (like Inheritance indeed may be the right choice for this problem. Still I'm not sure it will be practical to use separate classes for some methods in FL code. This is not well explored though, and I'm not sure in either case. Anyway what I originally asked may be useful in some cases, IMO. Would be cool if it was considered, or maybe already possible somehow. |
What I'm trying to say is that, if we forget about Classes for a moment, |
Related: #452 |
We recommend either using inheritance or type guards/invariants for cases like this. The method will be on your class at runtime no matter what |
In this example, can we somehow add a restriction for
getXMultBy
thatthis
must be an instance ofFoo<number>
, so the following code wouldn't type check?The text was updated successfully, but these errors were encountered: