strictFunctionTypes and Contravariance
What you'll learn: How strictFunctionTypes enforces correct variance checking for function parameter types to prevent runtime errors.
What Is This About?
When strictFunctionTypes is enabled in your tsconfig.json, TypeScript enforces contravariance for function parameters. This is a fancy term for a simple safety rule: if you're substituting one function for another, the substitute must accept at least as many types as the original.
Without this check, you could accidentally pass a function that expects something specific where a more general function is needed—leading to runtime crashes.
How Function Parameter Checking Works
Normally, you might expect that if Dog extends Animal, then a function accepting Dog could substitute for one accepting Animal. But with functions, it's backwards!
A function that accepts Animal (more general) can safely substitute for one that accepts Dog (more specific), because it can handle any dog and more. The reverse is unsafe.
Why This Matters
type Animal = { name: string };
type Dog = Animal & { bark: () => void };
let handleDog: (d: Dog) => void;
let handleAnimal: (a: Animal) => void;
// With strictFunctionTypes: ERROR
// handleDog = handleAnimal; // ✗ Animal handler can't guarantee it knows about bark()
// This direction is safe:
handleAnimal = handleDog; // ✓ Dog handler can work with any Animal
With strictFunctionTypes disabled, TypeScript would allow the unsafe assignment, potentially causing runtime errors when bark() is called on a plain Animal.
Key Takeaway: strictFunctionTypes prevents you from assigning functions with more specific parameter types where more general ones are expected, catching type mismatches that would otherwise cause runtime errors.