Sub topic 2
Function Parameters and `strictFunctionTypes`
Assume TypeScript generics, structural typing, assignability, and the strict compiler option.
Function parameters and `strictFunctionTypes`
A function that accepts an Animal can safely be used where a function accepting a Dog is expected. It can handle every Dog. The reverse is unsafe: a function that accepts only Dog cannot handle every Animal.
With strictFunctionTypes, TypeScript checks function-typed properties contravariantly.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface AnimalHandler {
handle: (animal: Animal) => void;
}
const dogHandler: { handle: (dog: Dog) => void } = {
handle: dog => dog.bark()
};
// Error: Dog is narrower than Animal
// const handler: AnimalHandler = dogHandler;Why method declarations stay bivariant
A method declaration uses older, more permissive checking. Its parameter is bivariant, meaning TypeScript may allow assignment in either direction.
interface AnimalMethods {
handle(animal: Animal): void;
}
const dogMethods: { handle(dog: Dog): void } = {
handle: dog => dog.bark()
};
const methods: AnimalMethods = dogMethods; // AllowedThis preserves compatibility with existing libraries, but it can permit an unsafe call. Prefer function-typed properties when strict parameter checking matters.
Arrays are covariant, but unsoundly
TypeScript treats Dog[] as assignable to Animal[]. This is covariance: the subtype relationship moves in the same direction.
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = dogs;
animals.push(new Animal()); // Allowed
dogs[1].bark(); // Runtime failureThe write through animals inserted a non-Dog value into dogs.
`ReadonlyArray` is safe
ReadonlyArray<T> does not provide methods that write elements. Therefore, covariance is safe.
const safeAnimals: ReadonlyArray<Animal> = dogs;
const first: Animal = safeAnimals[0];
// safeAnimals.push(new Animal()); // ErrorHow TypeScript measures variance
TypeScript examines where a type parameter appears:
| Use of `T` | Variance |
|---|---|
| Returned or read | Covariant |
| Accepted or written | Contravariant |
| Both read and written | Invariant |
The compiler usually infers this relationship automatically.
Declaring covariance with `out`
Use out to document and enforce that a type parameter is produced only.
interface Producer<out T> {
get(): T;
}
declare const dogs: Producer<Dog>;
const animals: Producer<Animal> = dogs; // OKIf T appears as an input, the annotation contradicts the structure and TypeScript reports an error.
Exercise
Why can Producer<Dog> be assigned to Producer<Animal>?
Show answer
Producer only outputs T, so it is covariant. A producer of Dogs can safely be used where a producer of Animals is expected.