Skip to content

'this' return type #1435

Closed
Closed
@jamiewinder

Description

@jamiewinder

Admittedly I haven't given this as much thought as it may need, but I thought it worth suggesting.

In JavaScript, it's common to return 'this' so the function can be chained. In most cases this can be easily defined:

class Obj
{
    public chainable(): Obj { ...; return this; }
}

However, if I extend the class:

class MegaObj extends Obj
{
    public doThing(): MegaObj { ...; return this; }
}

Then I can do:

var mo: MegaObj = ...
mo.doThing().chainable();

But I can't do...

mo.chainable().doThing();

Because 'chainable' returns 'Obj'. I think it'd be useful to be able to specify that the return type is the same as the object that the method was called on:

class Obj
{
    public chainable(): this  { ...; return this; }
}

class MegaObj extends Obj
{
    public doThing(): this  { ...; return this; }
}

var mo: MegaObj = ...
var mo2 = mo.chainable(); // mo2 is a MegaObj, because mo is a MegaObj
mo2.doThing();  // ok

Any feedback welcome, if only to inform me why this is a bad idea! Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions