Sub topic 10
Stricter Function Types, `bind`, `call`, `apply`, and `this`
This chapter assumes basic TypeScript functions, union types, and classes. It also assumes you know that strict: true enables a group of related compiler checks. The options here make function calls safer by checking parameter compatibility and the type of this.
Checking Function Parameters
With strictFunctionTypes, TypeScript checks whether one function can safely replace another. This matters when a function is passed as a callback.
A callback that accepts a general value can handle a specific value. The reverse is unsafe:
type Animal = {
name: string;
};
type Dog = Animal & {
bark(): void;
};
function visitAnimal(visit: (animal: Animal) => void): void {
visit({ name: "Milo" });
}
const printDog = (dog: Dog): void => {
dog.bark();
};
visitAnimal(printDog);The call is rejected because visitAnimal might pass an ordinary Animal, but printDog requires a Dog. The bark method might not exist.
A safe callback accepts the broader type:
const printAnimal = (animal: Animal): void => {
console.log(animal.name);
};
visitAnimal(printAnimal);The rule protects the function that will call the callback, rather than only checking whether the callback looks similar.
Checking `bind`, `call`, and `apply`
JavaScript lets you invoke a function with a chosen this value:
callinvokes a function immediately with separate arguments.applyinvokes it immediately with an array of arguments.bindcreates a new function withthisand possibly some arguments fixed.
strictBindCallApply checks the receiver and arguments for these operations.
function format(this: { prefix: string }, value: number): string {
return `${this.prefix}${value}`;
}
const settings = { prefix: "ID-" };
const boundFormat = format.bind(settings);
console.log(boundFormat(42));
console.log(format.call(settings, 7));
console.log(format.apply(settings, [9]));Incorrect arguments now produce errors:
format.call(settings, "seven");
format.apply(settings, ["nine"]);Without this option, these calls can lose the parameter information and become easier to misuse.
Making `this` Explicit
noImplicitThis reports an error when TypeScript cannot determine the type of this. Add a this parameter to a function to describe the expected receiver. The parameter is checked by TypeScript but does not appear in the emitted JavaScript.
type Counter = {
value: number;
increment(this: Counter, amount: number): void;
};
const counter: Counter = {
value: 0,
increment(amount) {
this.value += amount;
}
};
counter.increment(2);
console.log(counter.value);Arrow functions do not create their own this. They capture this from the surrounding scope, so use them when that behavior is intended.
Choosing the Options
| Option | Main protection |
|---|---|
| `strictFunctionTypes` | Prevents unsafe function parameter assignments |
| `strictBindCallApply` | Checks arguments and receivers for bind, call, and apply |
| `noImplicitThis` | Reports an untyped or incorrectly inferred `this` |
These checks are usually enabled by strict: true. Keeping them enabled exposes mistakes at compile time, before a callback receives an unexpected value or a method runs with the wrong receiver.
Exercise
Why is a function accepting Dog unsafe where a function accepting Animal is required?
Show answer
The caller may provide an Animal that is not a Dog, so the function could try to use Dog-only members that do not exist.