-
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
Polymorphic this with subclassing #17533
Comments
May be related to #16790 and/or #5863 (comment) |
Unfortunately this pattern has been incorrect but undetected. See #17509 (comment). |
Why are you overriding the definition anyway? |
In my use case, |
Gotcha - you can be more explicit about the type parameter and just use a type assertion to tell the type system that you know better in this case, but it isn't quite as safe I suppose. class Parent {
static create<T extends Parent>(this: { new (): T }): T {
return new this();
}
}
class Child extends Parent {
static create<T extends Child>(this: { new(): T}): T {
return super.create() as T;
}
} |
@DanielRosenwasser Thanks! That does work, until I add a property to the child class that doesn't exist on the parent: class Parent {
static create<T extends Parent>(this: { new (): T }): T {
return new this();
}
}
class Child extends Parent {
childProperty: string;
static create<T extends Child>(this: { new (): T }): T {
return super.create() as T;
}
}
Any ideas? (Also, if this needs to be closed and moved to a Stack Overflow or something, just let me know.) |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
This works and also provides access to any static members. type Constructor<T> = { new(): T };
class Parent {
a = 7;
static b = true;
static create<T extends Parent>(this: typeof Parent & Constructor<T>) {
return new this();
}
}
class Child extends Parent {
y = 42;
static z = 'foo';
static create<T extends Parent>(this: typeof Child & Constructor<T & Child>) {
this.z; (new this).y;
return super.create() as T;
}
} See [#23960]. |
@zamb3zi I don't have my original use case any more, but that looks pretty good, thanks! |
Using Polymorphic "this" for static members workaround from #5863 no longer works with subclassing in TypeScript 2.4.
TypeScript Version: 2.4.2
Code
Expected behavior:
Should not have type errors, which was the behavior in 2.3.4.
Actual behavior:
The text was updated successfully, but these errors were encountered: