Sub topic 10
Stricter function types, bind/call/apply, and this
This chapter covers three flags that "strict": true turns on: strictFunctionTypes, strictBindCallApply and noImplicitThis. All three concern functions. They decide when one function type can replace another, whether call, apply and bind are checked, and whether this can silently be any.
It assumes you can read basic TypeScript (interfaces, generics, arrow functions), have a working tsconfig.json with "strict": true, and know that JavaScript's this depends on how a function is called.
Where these flags sit
Each flag can be set individually, but turning on strict enables all of them. Setting one of them explicitly overrides what strict says for that flag alone.
| Flag | What it checks | Typical error |
|---|---|---|
| `strictFunctionTypes` | Parameter types of function values are compared contravariantly | Type '(d: Dog) => void' is not assignable to type '(a: Animal) => void' |
| `strictBindCallApply` | Arguments passed to `bind`, `call` and `apply` match the target function | Argument of type 'string' is not assignable to parameter of type 'number' |
| `noImplicitThis` | `this` must have a known type inside functions | 'this' implicitly has type 'any' |
strictFunctionTypes
Suppose a function expects an Animal. You can give it a Dog, because every dog is an animal. The reverse is unsafe. A function that needs a Dog may call bark(), so it must not be used where any Animal could arrive.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
type Handler<T> = (value: T) => void;
const handleDog: Handler<Dog> = (dog) => dog.bark();
const handleAnimal: Handler<Animal> = (animal) => console.log(animal.name);
// Safe: a handler for any Animal can also handle a Dog.
const okay: Handler<Dog> = handleAnimal;
// Error under strictFunctionTypes: handleDog may call bark() on a plain Animal.
const broken: Handler<Animal> = handleDog;The rule is called contravariance. Parameter types flow in the opposite direction to the types of the functions themselves. A Handler<Animal> is a subtype of Handler<Dog>, not the other way round.
Without the flag, TypeScript compares parameters bivariantly, so both assignments compile. The unsafe one then fails at runtime with "bark is not a function".
Methods are exempt
The check applies to function type properties and function types. It does not apply to declarations that use method syntax. This is deliberate. Many common patterns, such as Array<Dog> being assignable to Array<Animal>, rely on method bivariance.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
interface MethodStyle {
handle(value: Animal): void;
}
interface PropertyStyle {
handle: (value: Animal) => void;
}
const dogOnly = {
handle(value: Dog) {
value.bark();
},
};
const a: MethodStyle = dogOnly; // allowed: method syntax stays bivariant
const b: PropertyStyle = dogOnly; // error: property of function type is checked strictlyThe check follows the declaration of the target you assign to. If you want strict checking for a callback in an interface, write it as a property with an arrow type. If you want the looser behavior, use method syntax.
strictBindCallApply
Without this flag, call, apply and bind come from the global Function interface. They accept any arguments and return any. With the flag on, TypeScript uses the CallableFunction and NewableFunction interfaces, which are generic over the target's parameters and return type.
function add(a: number, b: number): number {
return a + b;
}
const sum = add.call(undefined, 1, 2); // number
const total = add.apply(undefined, [1, 2]); // number
const addFive = add.bind(undefined, 5); // (b: number) => number
console.log(sum, total, addFive(3));
add.call(undefined, 1, "2"); // error: string is not assignable to number
add.apply(undefined, [1]); // error: [number] is not assignable to [a: number, b: number]
addFive("3"); // error: the bound function remembers its remaining parametersbind computes a new function type. Binding 5 to a leaves (b: number) => number, so later calls are checked too.
One limit to know about: for overloaded functions, these methods only see the last overload signature. If bind or call complains about a function that is fine when called directly, check the overload list. A small wrapper arrow function, such as (x: string) => overloaded(x), avoids the problem and is often clearer.
noImplicitThis
Inside a function, this is decided by the caller. TypeScript can only help if it knows what this should be. With noImplicitThis, any use of this whose type would fall back to any is an error.
const counter = {
count: 0,
incrementLater() {
setTimeout(function () {
this.count++; // error: 'this' implicitly has type 'any'
}, 100);
},
};The inner function gets its own this, which setTimeout sets to something else at runtime. The usual fix is an arrow function, which keeps the this of the enclosing method:
const counter = {
count: 0,
incrementLater() {
setTimeout(() => {
this.count++;
console.log(this.count);
}, 100);
},
};
counter.incrementLater();Inside methods of an object literal, this is typed as the literal's type, so this.count is a number. In classes, this is the class instance type.
The this parameter
When a standalone function depends on this, declare it as a fake first parameter named this. It exists only for the type checker and is erased from the emitted JavaScript.
interface Person {
name: string;
}
function describe(this: Person, greeting: string): string {
return `${greeting}, ${this.name}`;
}
console.log(describe.call({ name: "Ada" }, "Hello"));
const greetAda = describe.bind({ name: "Ada" });
console.log(greetAda("Hi"));
describe("Hello"); // error: the 'this' context of type 'void' is not assignable to type 'Person'This combines with strictBindCallApply. call and bind check the this value you supply against the declared this type. bind also removes the this parameter from the resulting function type, so greetAda takes only greeting.
Common errors and fixes
- A callback typed for a subtype is rejected. The code is passing
(d: Dog) => voidwhere(a: Animal) => voidis expected. Widen the parameter type and narrow inside the callback, or make the expected type generic. thisisanyinside a callback. Use an arrow function, or give the function athisparameter.bindproduces an unexpected type. The function is probably overloaded. Wrap it in an arrow function.- Library code fails after enabling the flags. The flags apply to your code. If errors come from
.d.tsfiles innode_modules,skipLibCheckhides them, as covered in the chapter on interop and speed.
Turning the flags off during a migration
If an existing project has many violations, keep strict on and switch off only the flag that is causing trouble:
{
"compilerOptions": {
"strict": true,
"strictFunctionTypes": false
}
}Re-enable each flag once the errors are fixed. Of the three, strictBindCallApply and noImplicitThis tend to produce few errors. strictFunctionTypes can produce more in codebases with event systems or plugin registries.
Exercise
Given interface Box { put: (item: Animal) => void } and const dogBox = { put(item: Dog) { item.bark(); } }, does const box: Box = dogBox; compile under strictFunctionTypes? What changes if Box declares put(item: Animal): void instead?
Show answer
It does not compile. put in Box is a property with a function type, so parameters are compared contravariantly, and Dog is narrower than Animal. If Box declares put with method syntax, the assignment compiles because methods are compared bivariantly. That is unsafe if put is later called with an Animal that is not a Dog.
Exercise
What does function log(this: Console, text: string): void look like after it is compiled to JavaScript, and what is the type of log.bind(console)?
Show answer
The this parameter is erased, so the emitted function is function log(text) { ... }. With strictBindCallApply on, log.bind(console) has type (text: string) => void, because bind removes the this parameter and checks that the value passed matches Console.