this Parameter in Methods
You'll learn how to explicitly type this inside object and class methods so TypeScript enforces the correct calling context.
The Core Idea
In the previous lesson, you saw how JavaScript can lose track of this when methods are passed around. TypeScript lets you add a fake first parameter named this to any method. This parameter doesn't get passed at runtime—it's purely for TypeScript to verify that the function is called with the correct context.
When you write this: SomeType as the first parameter, you're telling TypeScript: "This function expects this to be of type SomeType when it runs."
Syntax
class Counter {
count = 0;
increment(this: Counter): void {
this.count++;
}
}
const counter = new Counter();
counter.increment(); // ✓ OK
const fn = counter.increment;
fn(); // ✗ Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'Counter'
The this: Counter parameter doesn't affect how you call the method—you still just write counter.increment(). But if you extract the method into a standalone variable, TypeScript catches the mistake.
Object Literal Methods
const timer = {
seconds: 0,
tick(this: { seconds: number }): void {
this.seconds++;
}
};
timer.tick(); // ✓ OK
const extracted = timer.tick;
extracted(); // ✗ Error: 'this' context incorrect
You explicitly declare what shape this must have. TypeScript verifies it at compile time.
Key Takeaway: Adding this: SomeType as the first parameter to a method tells TypeScript to enforce that the method is called with the correct context, catching dangerous standalone calls before runtime.