Sub topic 4
Methods and the this keyword
This chapter assumes you know basic TypeScript types, how JavaScript functions and objects work, and that you have seen a class with fields and a constructor. Here we focus on how methods are declared, how this is bound when they run, and the errors that appear when a method is detached from its object.
Declaring methods
A method is a function declared inside a class body. TypeScript checks its parameter types and return type like any other function. Inside a method, this has the type of the class, so the compiler knows which fields and methods are available.
class Counter {
private count = 0;
increment(step: number = 1): number {
this.count += step;
return this.count;
}
reset(): void {
this.count = 0;
}
}
const c = new Counter();
console.log(c.increment()); // 1
console.log(c.increment(5)); // 6
c.reset();
console.log(c.increment()); // 1Methods are placed on the class prototype, not on each instance. All instances share one copy of increment. This keeps memory use low, and it is the reason this matters: the same function runs for many objects, and this tells it which object it is working on.
How this is decided
In JavaScript, this is set by how a function is called, not by where it was written. When you write c.increment(), the object to the left of the dot becomes this. TypeScript assumes that this is the case when it type-checks the body of the method.
The problem appears when you separate the method from the object.
class Greeter {
constructor(private name: string) {}
greet(): string {
return `Hello, ${this.name}`;
}
}
const g = new Greeter("Ada");
console.log(g.greet()); // Hello, Ada
const detached = g.greet;
// detached(); // TypeError at runtime: Cannot read properties of undefined (reading 'name')Class bodies run in strict mode, so a plain call like detached() has no object on its left and this is undefined. TypeScript does not report this by default, because detached is just a function of type () => string. The error appears only when the code runs.
The same thing happens when you pass a method as a callback:
class Logger {
constructor(private prefix: string) {}
log(message: string): void {
console.log(`${this.prefix}: ${message}`);
}
}
const logger = new Logger("app");
["a", "b"].forEach(logger.log); // TypeError: this is undefinedThree ways to keep this
There are three common fixes. Each has different costs.
Wrap the call in an arrow function
Arrow functions do not have their own this. They use the this of the surrounding code. Wrapping the call keeps the method call in the form obj.method().
class Logger {
constructor(private prefix: string) {}
log(message: string): void {
console.log(`${this.prefix}: ${message}`);
}
}
const logger = new Logger("app");
["a", "b"].forEach((m) => logger.log(m));
// app: a
// app: bThis changes nothing in the class and works for any method. The caller has to remember to do it.
Use bind
bind returns a new function with this fixed. It is useful for a one-off fix, and you can also do it in the constructor.
const bound = logger.log.bind(logger);
["c", "d"].forEach(bound);With strictBindCallApply (part of strict), TypeScript checks the argument types of bind, call, and apply.
Define the method as an arrow function property
An arrow function stored in a field captures this when the instance is created.
class Button {
private clicks = 0;
constructor(private label: string) {}
handleClick = (): void => {
this.clicks++;
console.log(`${this.label}: ${this.clicks}`);
};
}
const b = new Button("save");
const handler = b.handleClick;
handler(); // save: 1
handler(); // save: 2This is safe to pass around, but it has costs. Each instance gets its own function object, so memory use grows with the number of instances. The function is an own property rather than a prototype method, so a subclass cannot call super.handleClick(), and overriding it is awkward. Use this form for event handlers and callbacks, and ordinary methods elsewhere.
| Approach | Safe to pass as callback | Shared on prototype | Works with `super.method()` |
|---|---|---|---|
| Normal method | No | Yes | Yes |
| Arrow function property | Yes | No | No |
| `bind` in constructor | Yes | Creates per-instance copy | Original stays on prototype |
| Wrapper arrow at call site | Yes | Yes | Yes |
Declaring this in a method
TypeScript lets you declare a fake first parameter named this. It is erased from the compiled output and exists only for checking. With it, the compiler rejects a detached call.
class Greeter {
constructor(private name: string) {}
greet(this: Greeter): string {
return `Hello, ${this.name}`;
}
}
const g = new Greeter("Ada");
console.log(g.greet()); // Hello, Ada
const detached = g.greet;
// detached();
// Error: The 'this' context of type 'void' is not assignable to method's 'this' of type 'Greeter'.This turns a runtime failure into a compile error. The cost is a more noisy signature, so it is most useful for methods that are known to be passed around.
The this return type
Inside a class, the type this refers to the type of the current instance, including subclasses. Returning this allows chained calls that keep the subclass type.
class QueryBuilder {
protected parts: string[] = [];
where(condition: string): this {
this.parts.push(`WHERE ${condition}`);
return this;
}
build(): string {
return this.parts.join(" ");
}
}
class UserQueryBuilder extends QueryBuilder {
onlyActive(): this {
return this.where("active = 1");
}
}
const sql = new UserQueryBuilder()
.where("age > 18")
.onlyActive()
.build();
console.log(sql); // WHERE age > 18 WHERE active = 1If where were declared to return QueryBuilder, the call to onlyActive() after .where(...) would fail to compile, because onlyActive does not exist on the base class.
Common errors
- Reading a field in a callback and getting
undefinedor aTypeError. The method was detached. Use one of the three fixes above. - Using an arrow function property and then trying to override it with a normal method in a subclass. TypeScript reports that the class defines the member as an instance property, so the override must also be a property.
- Using
functionexpressions inside a method. A nestedfunction () { this.x }gets its ownthis. Use an arrow function inside methods so thatthiscarries through.
class Totals {
private values = [1, 2, 3];
private sum = 0;
compute(): number {
this.values.forEach((v) => {
this.sum += v; // arrow function: this is still the Totals instance
});
return this.sum;
}
}
console.log(new Totals().compute()); // 6Exercise
A class Timer has a method tick() that increments this.seconds. The code setInterval(timer.tick, 1000) throws a TypeError when it first runs. Why does it fail, and what is one fix that keeps tick on the prototype?
Show answer
Passing timer.tick hands setInterval the bare function, so it is later called without an object on its left and this is undefined in strict mode. One fix is to wrap the call: setInterval(() => timer.tick(), 1000). Using timer.tick.bind(timer) also works.
Exercise
Why does a method that returns this support chaining on a subclass better than a method that returns the base class name?
Show answer
The this type stands for the type of the actual instance, including subclasses. A method declared to return this therefore gives back the subclass type, so subclass methods remain available later in the chain. A method declared to return the base class type loses the subclass methods in the chain.