Polymorphic this
Concept and syntax
A method return type this preserves the actual receiver subtype. Returning this supports fluent APIs where a subclass-specific method can follow a base method. Returning the base class type instead loses that subtype information even if the runtime value remains the same object.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
class Base {count=0;add(n:number):this{this.count+=n;return this;}}class Child extends Base {label(){return "n="+this.count;}}console.log(new Child().add(3).label());Expected output:
n=3Common mistake
Intentionally invalid; compile separately and do not execute.
class Base {add():Base{return this;}}class Child extends Base {label(){return "child";}}new Child().add().label();Expected diagnostic: TS2339. The return contract exposes only Base. Use this for a fluent receiver-preserving method.
Practice and recap
Chain two add calls on Child and read its label.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Polymorphic this — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
class Base {count=0;add(n:number):this{this.count+=n;return this;}}class Child extends Base {label(){return "n="+this.count;}}console.log(new Child().add(3).label());Which diagnostic and explanation match the rejected example under the lesson settings?
class Base {add():Base{return this;}}class Child extends Base {label(){return "child";}}new Child().add().label();