-
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
Method override error with generic this- only for non-overloaded methods. #23960
Comments
If that were allowed there could be an error at runtime like so: class C {
x: number;
f<T extends C>(this: T, arg: keyof T) { }
}
class D extends C {
y: string;
f<T extends D>(this: T, arg: keyof T) {
// Allowed because `T` extends `D`.
this.y.toUpperCase();
}
}
function f(c: C) {
// We think this is OK to do because `C#f` can take a `this` of any `T` extending `C`, including `C` itself.
// Though note that TypeScript doesn't actually have a type-safe way to provide a `this` argument -- `call` just takes `...args: any[]`.
c.f.call(new C(), "x");
}
f(new D()); // Allowed because `D` extends `C`. Overloading breaks it because overloading is unsafe in general. |
Thanks but your example does not produce a runtime error. It's clear that use of call, apply and bind is not type safe, so there are any number of ways to produce a runtime error that way. |
I tested the example and it shows a runtime error for me?
True, but that's only necessary because of the class C {
x: number;
f<T extends C>(self: T) { }
}
class D extends C {
y: string;
f<T extends D>(self: T) {
self.y.toUpperCase();
}
}
function f(c: C) {
c.f(new C());
}
f(new D()); |
Exactly. I think the problem is that class C {
x: number;
f(arg: keyof this) { }
}
class D extends C {
y: string;
f(arg: keyof this) { }
} |
Why would you write |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
Why is this closed as
IMO |
Filed #26631 with a minimal repro. |
TypeScript Version: 2.8.3
Search Terms: generic this, override, polymorphic this
Code
Expected behavior:
Non-static case: behavior should be the same, with and without use of overloading. It seems as if the overloaded behavior is correct.
T
should be treated as if it were polymorphic this.Static case: this is more of a problem because this pattern seems to be the current best practice for achieving static polymorphic this (see: [#5863]). Both of the workarounds ought not be needed.
The text was updated successfully, but these errors were encountered: