Prevent unsafe callback assignment
A callback type accepts a union, but an implementation accepts only one member of that union.
TypeScript · Const
strictFunctionTypes makes function parameter comparisons contravariant instead of bivariant, catching unsafe callback assignments. It is enabled by strict mode but does not apply to methods or constructors.
The strictFunctionTypes compiler option makes function-parameter comparison contravariant instead of bivariant. It prevents assigning a callback that accepts only a narrower type to a callback type that may pass a broader type; method and constructor declarations remain exempt.
"strictFunctionTypes": true| Name | Type | Description |
|---|---|---|
strictFunctionTypes | boolean | Boolean compiler setting that controls strict checking of function parameter positions. |
function handleString(value: string) {
console.log(value.toLowerCase());
}
type StringOrNumberHandler = (value: string | number) => void;
// Error: a number could reach handleString.
const handler: StringOrNumberHandler = handleString;With strictFunctionTypes enabled, TypeScript rejects this unsafe assignment because the declared handler may receive a number.
A callback type accepts a union, but an implementation accepts only one member of that union.
A large project wants stricter function compatibility checks as part of its standard compiler policy.
A compatibility-sensitive generic class or interface relies on method declarations rather than function-valued properties.
It changes function-parameter checking from bivariance to contravariance. A callback accepting only string cannot implement a callback type that might invoke it with string or number, because that assignment is unsafe.
Follow-up: Why are methods excluded? The documented reason is to preserve compatibility for generic classes and interfaces such as Array<T>, whose existing relationships could otherwise become unsafe or break.
With the option enabled, assigning (x: string) => void to (x: string | number) => void is rejected because the target could call the function with a number. This catches a call that would otherwise fail at runtime.
Follow-up: What happens when the option is disabled? The assignment is permitted because default checking treats the situation as possibly sound, even though it is not provably safe.
The option belongs to TypeScript's strict family and is enabled by strict mode by default. It can also be controlled directly in tsconfig.json or through the compiler command line.
Follow-up: How can a project selectively disable it? Set strictFunctionTypes to false, or pass --strictFunctionTypes false on the command line.
strictstrictNullChecksType CompatibilityFunction Parameter BivarianceComparer<T>