What is the this type in TypeScript?
Why Interviewers Ask This
Mid-level TypeScript roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
Answer
TypeScript provides a special this type that represents the type of the current object in methods and functions, resolved polymorphically. Polymorphic this: in a base class method, returning this typed as this means subclasses automatically get the correct return type: class Builder { setValue(v: string): this { this.value = v; return this; } } — if you subclass Builder and call setValue(), the return type is the subclass type, not just Builder. Enables fluent builder patterns where methods chain correctly through inheritance. this parameter: TypeScript allows declaring an explicit this parameter as the first parameter of a function to specify the required type of this when the function is called: function greet(this: User, greeting: string): void { console.log(greeting + this.name); }. This is a TypeScript-only parameter — it is erased from the compiled output. It prevents calling the function in contexts where this would have the wrong type.
Pro Tip
This topic has TypeScript-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.
Previous
What is the difference between type widening and type narrowing?
Next
What is strict null checks and why is it important?