Skip to content

A syntax for returning "this" for method call chaining would be great #7620

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

Closed
philthy256 opened this issue Mar 21, 2016 · 3 comments
Closed
Labels
Question An issue which isn't directly actionable in code

Comments

@philthy256
Copy link

When you've got a bit of inheritance going on, there can be limits to what you can do with method chaining. Say you've got these two classes:

class Animal {
    public sleep() : Animal {
        return this;
    }
}

class Elephant extends Animal {
    public squirtWithTrunk(): Elephant {
        return this;
    }
}

Given an instance of Elephant, you could do this:
myElephant.squirtWithTrunk().sleep()

but you couldn't do this:
myElephant.sleep().squirtWithTrunk()

Because Animal doen't have a "squirtWithTrunk" method.

Seems fair enough, but given how much code space method chaining can save, and how much that can matter in JavaScript, it's a shame. And obviously in raw JavaScript this sort of thing just works.

If the following syntax were allowed, and "this" could be passed through a method chain without its type being narrowed to ancestor types, I think that might be quite nice:

class Animal {
    public sleep() : this {
    }
}

class Elephant extends Animal {
    public squirtWithTrunk(): this {
    }
}

I don't know how feasible that would be from a compiler point of view, but as a user of the language I'd find it very useful. In the last code snippet I imagine that the return statement would be disallowed, and that the returned value would always be the current object.

@sandersn
Copy link
Member

TypeScript already works this way. You do have to return this at the end of each method though.

@sandersn
Copy link
Member

See #4910

@philthy256
Copy link
Author

@sandersn That's awesome, thank you!

The following works a treat - great stuff:

class Animal {
public sleep() {
return this;
}
}

class Elephant extends Animal {
public squirtWithTrunk() {
return this;
}
}

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Mar 22, 2016
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants