Question presented to candidate:
"What is the polymorphic this type in TypeScript? Show a fluent builder where a subclass adds methods, and explain why returning this keeps the chain typed when returning the class name does not."
What a strong answer should cover:
- Inside a class or interface,
thisused as a type means "the type of the object the member was called on," which is the subclass when called on a subclass instance - Fluent APIs: a base method declared
(): thisreturns the subclass type, so subclass methods stay available after base-class calls in a chain; an explicit class-name return type loses them thisalso works in parameter positions (equals(other: this)) and in interfaces (tap(fn: (self: this) => void): this)this-based type guards (isFile(): this is FileNode) narrow the receiver- Limits:
thisbehaves like a type parameter, soreturn new Base()is not assignable tothis; cloning needs a prototype copy or similar - Not to be confused with a
thisparameter (function f(this: Window)), which types the receiver of a plain function
Code / implementation expected: Yes β a two-level builder whose base methods return this, chained through a subclass method.