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();- ✓Correct answer: Polymorphic
this: a method chain keeps the subclass type - 2The method always returns the base class type
Query - 3It's an error:
thiscan't be used as a type
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.