Sub topic 12
Typing `this` in TypeScript
This chapter assumes you know JavaScript functions, objects, and TypeScript object types. It also assumes your project uses strict checking, especially noImplicitThis.
In JavaScript, this usually refers to the object used before the dot in a method call:
const person = {
name: "Ada",
describe() {
return `I am ${this.name}`;
},
};
person.describe(); // this is personTypeScript can describe the type that a function expects as its this value. Add a special parameter named this as the first parameter:
function describe(this: { name: string }): string {
return `I am ${this.name}`;
}
const person = {
name: "Ada",
describe,
};
console.log(person.describe()); // I am Ada
// describe(); // Error: the function needs a this valueThe this parameter is only a type annotation. TypeScript removes it when it emits JavaScript. It does not become a normal argument.
The receiver must be present
The object before the dot is called the receiver. A function with a typed this parameter must be called with a compatible receiver.
type Account = {
owner: string;
rename(this: Account, owner: string): void;
};
function rename(this: Account, owner: string): void {
this.owner = owner;
}
const account: Account = {
owner: "Ada",
rename,
};
account.rename("Grace");
console.log(account.owner); // Grace
const detached = account.rename;
// detached("Lin"); // Error: no Account receiver
detached.call(account, "Lin");
console.log(account.owner); // Lincall invokes a function with an explicitly supplied this value. The function still receives "Lin" as its ordinary argument.
A detached method can also lose its receiver at runtime:
const method = account.rename;
// method("Turing"); // Would have undefined this in strict JavaScriptThe type error is useful because it identifies this common bug before the code runs.
Choosing `this: void`
Some functions should never use a receiver. Writing this: void documents that rule and prevents callers from depending on this.
type ClickHandler = (this: void, label: string) => void;
const handler: ClickHandler = function (label) {
console.log(label);
// this is not available here
};
handler("Save");This is useful for callbacks that might be passed around independently. It prevents an implementation from accidentally depending on how a library invokes it.
Arrow functions capture `this`
An arrow function does not create its own this. It captures this from the surrounding scope. You cannot add a this parameter to an arrow function.
class Timer {
seconds = 0;
start(): void {
setTimeout(() => {
this.seconds += 1;
}, 1000);
}
}The arrow callback keeps the Timer instance as this. A regular function callback would receive a different this value, or no useful receiver, depending on the API.
Use a regular function when the caller should provide this. Use an arrow function when the function should keep the surrounding this.
A practical checklist
- Add
this: SomeTypewhen a standalone function requires a receiver. - Put the
thisparameter before all ordinary parameters. - Use
this: voidfor callbacks that must not depend on a receiver. - Remember that extracting a method can lose its receiver.
- Use an arrow callback when you need to preserve the surrounding
this. - Treat
thisas a runtime calling convention, not as an ordinary argument.
Exercise
Why does account.rename("Grace") type-check while const f = account.rename; f("Grace") does not, when both refer to the same function?
Show answer
The method call supplies account as the function's this receiver. The detached call supplies no Account receiver, so TypeScript reports an error and strict JavaScript would not provide the expected object at runtime.