Sub topic 5
Function parameters and strictFunctionTypes
This chapter assumes you know generics, interfaces, function types, and structural assignability. It also assumes you have met the Animal and Dog pair and the idea of contravariance from the earlier chapters. Here you will see how the compiler applies contravariance to function types, what the strictFunctionTypes flag changes, and how to read the errors it produces.
Recap: the setup
The examples use the same pair as before. Dog is a subtype of Animal, so a Dog can go anywhere an Animal is expected, but not the other way around.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}Assigning one function type to another is a question of assignability, like any other. The compiler compares the two signatures piece by piece, and the parameters and the return type follow different rules.
The rule for functions
When the compiler checks whether a source function type S is assignable to a target function type T, it asks two separate questions:
- Parameters. Can every argument that a caller may pass to
Tbe safely accepted byS? So each parameter type ofTmust be assignable to the matching parameter type ofS. The direction reverses. This is contravariance. - Return type. Can the value
Sreturns be used whereverT's result is expected? SoS's return type must be assignable toT's return type. The direction is preserved. This is covariance.
The return half is easy to see:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
type MakeDog = () => Dog;
type MakeAnimal = () => Animal;
declare const makeDog: MakeDog;
const makeAnimal: MakeAnimal = makeDog; // OK: a Dog is an AnimalA caller of makeAnimal expects an Animal, and a Dog is one. The parameter half is the part that needs the flag.
Parameters: contravariance in action
A function that accepts any Animal can stand in wherever a function accepting only Dog is required. Every Dog it receives is an Animal, so it can handle it.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
type Handler<T> = (value: T) => void;
const handleAnimal: Handler<Animal> = (a) => console.log(a.name);
const handleDog: Handler<Dog> = handleAnimal; // OK: contravariant
const handleDogOnly: Handler<Dog> = (d) => console.log(d.bark());
// const unsafe: Handler<Animal> = handleDogOnly;
// Error under strictFunctionTypes: an Animal has no bark()If the commented line were allowed, unsafe(new Animal()) would call bark() on an object that has no such method. The compiler rejects the assignment because it can prove this could happen.
What the flag changes
strictFunctionTypes was added in TypeScript 2.6 and is part of the strict family. Setting "strict": true turns it on.
{
"compilerOptions": {
"strict": true
}
}You can also enable or disable it on its own with "strictFunctionTypes": true or false.
| Setting | Parameter check for function types | Result for `Handler<Dog>` to `Handler<Animal>` |
|---|---|---|
| `strictFunctionTypes: true` | Contravariant only | Error |
| `strictFunctionTypes: false` | Bivariant (either direction passes) | Accepted |
Bivariant means the compiler accepts the assignment if the parameter types are related in either direction. The older behavior was a deliberate compromise. It kept common patterns working, such as passing a handler for a specific event type where a handler for a general event type is expected. The cost was that the unsafe call above compiled without complaint.
The return type is covariant in both modes. The flag affects parameters only.
Reading the error
With the flag on, assigning Handler<Dog> to Handler<Animal> produces an error shaped like this:
Type 'Handler<Dog>' is not assignable to type 'Handler<Animal>'.
Types of parameters 'value' and 'value' are incompatible.
Property 'bark' is missing in type 'Animal' but required in type 'Dog'.Read it from the bottom. The last line names the actual mismatch: the target will pass an Animal, and the source needs a Dog. The middle line tells you the problem is in the parameters, not the return type.
Callbacks: two reversals make a forward direction
Parameter checking is applied recursively. When a parameter is itself a function type, its own parameters get reversed again. Two reversals cancel, so a type used inside a callback parameter behaves covariantly.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
type EachDog = (callback: (d: Dog) => void) => void;
type EachAnimal = (callback: (a: Animal) => void) => void;
declare const eachDog: EachDog;
const eachAnimal: EachAnimal = eachDog; // OKThis is sound. Whoever calls eachAnimal passes a callback that accepts any Animal. eachDog will only ever invoke that callback with Dog values, which the callback can handle. In the terms from the earlier chapters, Dog here sits in an output position of the outer function (it is handed to the callback), so the type is covariant in it.
A quick way to count: each time a type appears as a function parameter, flip the direction once. Appearing as a return type does not flip it.
Which function types are checked strictly
The strict check applies to function types that are not written as method or constructor declarations. That covers:
- Function type aliases such as
type Handler<T> = (value: T) => void. - Properties with a function type, such as
handle: (a: Animal) => void. - Call signatures in interfaces, such as
{ (value: T): void }. - Function expressions and arrow functions.
It does not apply to comparisons that originate in a method declaration, written as handle(a: Animal): void, or in a constructor declaration. Those keep the bivariant check even with the flag on. The next chapter explains why. For now, notice that two declarations that look equivalent behave differently:
// Compile with "strict": true (or "strictFunctionTypes": true)
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface FnProp {
handle: (a: Animal) => void;
}
interface Meth {
handle(a: Animal): void;
}
declare const dogFnProp: { handle: (d: Dog) => void };
declare const dogMeth: { handle(d: Dog): void };
// const p: FnProp = dogFnProp; // Error: parameter checked contravariantly
const m: Meth = dogMeth; // OK: method parameters stay bivariantPractical consequences
- Event handlers and callbacks. A handler for a general type can be used for a specific one, but not the reverse. If the compiler rejects a handler, check whether you are trying to pass a narrow handler where a wide one is expected.
- Generic aliases. For
type Handler<T> = (value: T) => void,Tappears only in a parameter position. The compiler therefore treatsHandler<T>as contravariant inT. That matches what you saw in theHandler<Animal>andHandler<Dog>example. - Fixing an error. The error is usually correct. Typical fixes are widening the handler's parameter type, narrowing the target type, or checking the value at runtime before calling
bark(). - Turning the flag off. Disabling
strictFunctionTypesremoves the error but not the bug. Prefer fixing the types. If a migration forces a temporary opt-out, leave the otherstrictflags on.
Exercise
With "strict": true, which of these assignments compile? (a) const f: (x: Animal) => void = (d: Dog) => {}; (b) const g: (x: Dog) => void = (a: Animal) => {}; (c) const h: () => Animal = () => new Dog(); Explain each in terms of parameter and return checks.
Show answer
(a) Does not compile. The target passes an Animal, but the source requires a Dog, so the target parameter type Animal is not assignable to Dog and the contravariant check fails. (b) Compiles. The target passes a Dog, and the source accepts any Animal, so Dog is assignable to Animal. (c) Compiles. Return types are covariant, and the source returns a Dog, which is assignable to Animal.
Exercise
Given type Subscribe = (listener: (event: Animal) => void) => void;, is a function of type (listener: (event: Dog) => void) => void assignable to Subscribe? Why?
Show answer
Yes. The check on the outer parameter reverses once: the target's listener type (event: Animal) => void must be assignable to the source's listener type (event: Dog) => void. That check reverses again on event, so Dog must be assignable to Animal, which it is. Two reversals produce a covariant position for the event type.