Polymorphic this in TypeScript -


i'm trying think "textbook" use case polymorphic this , isn't working , can't figure out. imagine have abstract base class cloneable, e.g.:

abstract class x {     abstract clone(): this; } 

now want implement base class provides clone implementation:

class y extends x {     constructor(private x: number) { super() }     clone(): { return new y(this.x + 1); } } 

when this, error says type y not assignable type 'this'. i'm totally confused. want convey here type constraint if subclass of x has clone method invoked, type of thing identical subtype. isn't polymorphic this for? doing wrong here?

here link code in typescript playground.

no, things right now, it's not supported use case type. method this return type should return instance of derived class if method not overridden in derived class - see code in answer example justifies this.

in other words, given abstract clone(): this declaration, code must valid if z not override clone itself, implementation of clone in y breaks it.

class z extends y {     f() {         let c: z = this.clone();     } } 

so looks method this return type should return this.

update: found open issue use case on github, marked 'accepting pull requests'. i'm not sure if intend support it, or plan fix clonenode in compiler in other way.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -