-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
this type is not assignable to the same property in base type #41181
Comments
The TypeScript version you use is fairly outdated. You should consider updating. The error is correct, what you want won't work. Just consider this example:
I can't think of a way this would work as you want. When implementing your clone method you can't know the constructor of Your best option is to have |
@MartinJohns The version must have been a copy&paste mistake, I tested it with TypeScript 4.0.2. To your example: I thought that polymorphic |
But your method doesn't return the polymorphic But then you end up with the other issue that you can't possibly know the constructor of
You have no way of knowing the constructor of |
Probably what you want to do is this interface Cloneable<T> {
clone(): T
}
class A implements Cloneable<A> {
constructor(readonly a: number){}
clone(): A {
return new A(this.a)
}
} |
Thanks, @RyanCavanaugh I'm aware of that solution, but hoped to be able to avoid the (somewhat redundant) Type parameter that is always of the same as the class that implements the interface. |
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes. |
TypeScript Version: 4.0.2
Search Terms: this type assignable same property base subtype
The following should work with polymorphic
this
:A variant with
clone(): this
in classA
also doesn't work (but with a different error message).Expected behavior:
The code should compile without error, so that
clone
in the classA
actually returns typeA
.Actual behavior:
Playground Link: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgMIBsD2IJwEbooDeAUMsgljgBQCUAXMmABbADOJAviSZXG22QBBZMAC2AB0JiI4QRmy4CxMhWxswUAK4IwmKNSi4AJtnQBPZHEYgtYvNFpFuqyorqMRpcuSNgtUCDIOADuwtQs7AB0cLSq3JxAA
Related
#283
The text was updated successfully, but these errors were encountered: