Sub topic 10
Parameter variance and strictFunctionTypes
This chapter assumes you know how assignability works for object shapes and that you can read basic function types in TypeScript. It also assumes you know what interface Dog extends Animal means. Here you will learn which direction the checker compares parameters and return types, what the strictFunctionTypes compiler flag changes, and where TypeScript still allows unsound assignments on purpose.
Variance in one paragraph
Variance describes how a relationship between two types carries over to types built from them. Suppose Dog is assignable to Animal. Then you can ask whether Box<Dog> is assignable to Box<Animal>, whether (x: Dog) => void is assignable to (x: Animal) => void, and so on. There are four possible answers:
- Covariant: the direction is preserved.
DogtoAnimalgivesF<Dog>toF<Animal>. - Contravariant: the direction is reversed.
DogtoAnimalgivesF<Animal>toF<Dog>. - Bivariant: either direction is accepted.
- Invariant: neither direction is accepted. The types must match exactly.
Function types mix these. Their return types are covariant, and their parameters are contravariant when strictFunctionTypes is on.
Return types are covariant
A function is a safe substitute if it gives back at least what the caller expects. A function that returns a Dog can stand in for one that returns an Animal, because every Dog is an Animal. The reverse is unsafe.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
type MakeAnimal = () => Animal;
type MakeDog = () => Dog;
const makeDog: MakeAnimal = (): Dog => ({ name: "Rex", bark() {} }); // OK
const makeAnimal: MakeDog = (): Animal => ({ name: "Generic" });
// Error: Property 'bark' is missing in type 'Animal' but required in type 'Dog'.The caller of MakeDog may call .bark() on the result, so a function that returns a plain Animal would break it.
Parameters are contravariant
Parameters work the other way, because they describe what the function can accept. A function that accepts any Animal can safely be used where a function that only receives Dog values is expected. Every Dog it receives is an Animal, so it can handle it.
// tsconfig: "strict": true (includes strictFunctionTypes)
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
let feedDog: (d: Dog) => void = (a: Animal) => {}; // OK
let feedAnimal: (a: Animal) => void = (d: Dog) => {};
// Error under strictFunctionTypes: parameter types are checked contravariantlyThe second assignment is rejected because a caller of feedAnimal may pass a cat. The assigned function would then call d.bark() on something that cannot bark.
A practical rule: when you assign function S to a target function type T, each parameter type of T must be assignable to the matching parameter type of S, and the return type of S must be assignable to the return type of T.
Correction: the diagram must follow the required fence format, so it is given below.
What strictFunctionTypes changes
Before TypeScript 2.6 there was no such flag, and parameters were compared bivariantly. Both of the assignments above were accepted. The strictFunctionTypes flag turns on contravariant parameter checking. It is part of strict, so most modern projects have it on already.
{
"compilerOptions": {
"strict": true
}
}You can also enable it alone with "strictFunctionTypes": true. Turning it off restores bivariant parameters everywhere, which hides real bugs. Leave it on and fix the errors it reports.
A realistic case: event handlers
The flag matters most in code that registers callbacks. Here Listener<BaseEvent> is a function that accepts any base event, so it is safe to register where click events are expected. The reverse is not.
interface BaseEvent {
type: string;
}
interface ClickEvent extends BaseEvent {
x: number;
y: number;
}
type Listener<E> = (event: E) => void;
const clickListeners: Listener<ClickEvent>[] = [];
const anyListeners: Listener<BaseEvent>[] = [];
const logType: Listener<BaseEvent> = (e) => console.log(e.type);
const logX: Listener<ClickEvent> = (e) => console.log(e.x);
clickListeners.push(logType); // OK: it accepts every ClickEvent
anyListeners.push(logX);
// Error: Argument of type 'Listener<ClickEvent>' is not assignable to
// parameter of type 'Listener<BaseEvent>'.If the second push were allowed, an event with no x property could reach logX, which would print undefined.
Where bivariance remains: method syntax
The flag does not apply everywhere. It applies to function types written as function type literals, such as (a: Animal) => void, and to properties declared with them. It does not apply to members declared with method syntax, or to constructor declarations. Those parameters stay bivariant.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
interface WithProperty {
feed: (a: Animal) => void;
}
interface WithMethod {
feed(a: Animal): void;
}
const dogOnly = (d: Dog): void => {
d.bark();
};
const strict: WithProperty = { feed: dogOnly };
// Error under strictFunctionTypes: 'Animal' is missing 'bark'
const loose: WithMethod = { feed: dogOnly }; // OK: method parameters are bivariant
loose.feed({ name: "Generic" }); // compiles, then throws TypeError: d.bark is not a functionThe two interfaces describe the same call, but the checker treats them differently. The method form is lenient. The property form is strict.
Why the exception exists
The exception keeps common patterns working. The main one is that Array<T> should stay covariant in T, so a Dog[] can be passed to a function that takes Animal[]. Methods such as push(...items: T[]) have T in a parameter position. If method parameters were strictly contravariant, Dog[] would not be assignable to Animal[], and a lot of everyday code would break.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
const dogs: Dog[] = [{ name: "Rex", bark() {} }];
const animals: Animal[] = dogs; // OK: arrays are covariant in practice
animals.push({ name: "Cat" }); // compiles: a cat is now in the dogs array
dogs[1].bark(); // TypeError at runtime: dogs[1].bark is not a functionThis is a known hole, and TypeScript accepts it for convenience. Read-only access is safe, but writing through a wider alias is not.
Summary of positions
| Position | Variance | Notes |
|---|---|---|
| Function return type | Covariant | Source may return a subtype. |
| Function parameter (function type, property) | Contravariant | Needs `strictFunctionTypes`. |
| Method parameter | Bivariant | Exempt from `strictFunctionTypes`. |
| Constructor parameter | Bivariant | Also exempt. |
| Mutable property or array element | Covariant | Unsound for writes, accepted on purpose. |
Fewer parameters are still fine
Variance concerns the parameter types. Parameter count follows a separate rule. A function that declares fewer parameters than the target is always acceptable, because it ignores the extra arguments. A function that requires more is not.
type Handler = (event: string) => void;
const ignoresArgs: Handler = () => {}; // OK: fewer parameters are allowed
const needsMore: Handler = (event: string, extra: number) => {};
// Error: the target supplies only one argumentDeclaring variance explicitly
For generic interfaces and type aliases, TypeScript 4.7 added the out and in modifiers on type parameters. They state the variance you intend, and the compiler reports an error if the declaration contradicts it. They also let the checker skip structural comparison of members, which can speed up checking large generic types.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
interface Producer<out T> {
get(): T;
}
interface Consumer<in T> {
accept(x: T): void;
}
declare const dogProducer: Producer<Dog>;
const animalProducer: Producer<Animal> = dogProducer; // OK: covariant
declare const animalConsumer: Consumer<Animal>;
const dogConsumer: Consumer<Dog> = animalConsumer; // OK: contravariant
declare const dogConsumer2: Consumer<Dog>;
const bad: Consumer<Animal> = dogConsumer2;
// Error: Consumer<Dog> is not assignable to Consumer<Animal>The annotation on Consumer<in T> also holds even though accept uses method syntax. The in modifier makes the comparison strictly contravariant for that type parameter.
Common mistakes
- Reading the direction backwards. To check a callback parameter, ask whether the target's parameter type fits into the source's parameter type, not the other way around.
- Assuming
strictFunctionTypescovers methods. It does not. Method-style members stay bivariant, so mismatches there are not reported. - Casting away the error. Writing
(a: Animal) => ...as(d: Dog) => ...silences the checker without fixing the underlying risk. Widen the parameter type or narrow the target instead. - Trusting array covariance for writes. Pass
readonly Animal[]to functions that only read. This documents that the function will not push unrelated subtypes into your array.
Exercise
Given interface Animal { name: string } and interface Dog extends Animal { bark(): void }, with strict on, which of these assignments compile? (a) const f: (x: Dog) => Animal = (x: Animal): Dog => ({ name: "a", bark() {} }); (b) const g: (x: Animal) => Dog = (x: Dog): Animal => x;
Show answer
(a) compiles. The source parameter Animal is wider than the target parameter Dog, which is allowed because parameters are contravariant. The source return Dog is assignable to the target return Animal, which is allowed because returns are covariant. (b) fails on both counts. The source parameter Dog is narrower than the target's Animal, and the source return Animal is wider than the target's Dog.
Exercise
An interface declares onChange(value: Animal): void. You assign an object whose onChange takes (value: Dog) => void. It compiles with strict on. Why, and how would you make the compiler reject it?
Show answer
Members declared with method syntax are exempt from strictFunctionTypes, so their parameters are compared bivariantly and Dog versus Animal is accepted in either direction. To get a strict check, declare the member as a property with a function type: onChange: (value: Animal) => void.