What is the this type in TypeScript?
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.
Previous
What is the difference between type widening and type narrowing?
Next
What is strict null checks and why is it important?