TypeScript · Senior · Question 22 of 75

What does a this return type give you in a class method?

class Query {
  where(c: string): this { /* ... */ return this; }
}
class UserQuery extends Query { active(): this { return this; } }
new UserQuery().where('x').active();

Explanation

If where returned Query, .active() wouldn't be available after it. Polymorphic this is handy for fluent APIs and builders. There's also this is T in type guard methods.

Further reading

Problem with a question

TypeScript · Senior · question 22

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz