Skip to the solution
MediumFrontend10 min read

What is a polymorphic 'this' type?

346 views

The problem

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, this used 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 (): this returns the subclass type, so subclass methods stay available after base-class calls in a chain; an explicit class-name return type loses them
  • this also 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: this behaves like a type parameter, so return new Base() is not assignable to this; cloning needs a prototype copy or similar
  • Not to be confused with a this parameter (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.

  • this-type

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptA fluent builder: returning this vs the class name
TypeScriptthis in parameters, this type guards, clone() and the this parameter

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 51 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What is an index signature?

Continue