-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Return type of inherited methods breaks function chaining #275
Comments
I believe the general idea here is that you should be able to say that a class method returns the type of whatever object it was invoked on; we generally called this "this-typing" in design discussions when it came up. It's certainly a useful and common pattern. We'd like to see a proposal here (see https://github.com/Microsoft/TypeScript/wiki/Writing-Good-Design-Proposals) that defines syntax, type rules, etc. |
If the base class is used like an abstract class and the child class is never inherited, then this is an ok workaround: // http://stackoverflow.com/a/23024723/188246
class Base<T extends Base<any>> {
promise() : T {
return <any> this;
}
}
class Child extends Base<Child> {
public myString: string;
}
new Child().promise().myString; // works |
I could maybe see this feature working if something like default type parameters or generic parameter overloads (#209) were implemented. Rough example... very ugly though: class Base<T extends Base<any> = Base> {
promise() : T {
return <any> this;
}
}
class Child<T extends Child<any> = Child> extends Base<T> {
public myString: string;
}
class ChildChild<T extends ChildChild<any> = ChildChild> extends Child<T> {
public otherString: string;
}
new Child().promise().myString;
new ChildChild().promise().otherString; |
Hey everyone. Was there any progress on this in 1.4.1? |
+1 |
Would love to get this one too. 👍 |
Related: #3694 |
As for a full proposal, I'd like to see how the community reacts to this vs the other bug first. A proposal would be better after that. |
this is tracked by #3694 |
Suppose I want to make a class with tons of chainable methods, like setters. This works fine.
This allows us to create and setup a new Chainable much more concisely than would otherwise be possible.
The problem occurs when we want to extend our Chainable class and maintain the chainability of the function calls.
There is a workaround, but it is verbose and boiler-platey:
When set1 is called on a SuperChainable and returns
this
, thethis
really is a SuperChainable and not a Chainable. So it seems to me that the typescript compiler is in error in treating the return value as a Chainable. If this error were fixed, it would be much easier to create inherited objects that support method chaining.(copied over from now-closed issue on codeplex: https://typescript.codeplex.com/workitem/2332)
The text was updated successfully, but these errors were encountered: