How does TypeScript check compatibility between two function types, particularly regarding parameter counts?
Short answer
A function type A is assignable to function type B if A's parameters are compatible with B's (contravariantly, roughly) AND A doesn't require MORE parameters than B provides — meaning a function taking fewer parameters can safely stand in for one expecting more, since extra…
Advertisement
AModel answer
A function type A is assignable to function type B if A's parameters are compatible with B's (contravariantly, roughly) AND A doesn't require MORE parameters than B provides — meaning a function taking fewer parameters can safely stand in for one expecting more, since extra arguments are simply ignored, but not the reverse.
type Handler = (event: Event, index: number) => void;
const handler: Handler = (event) => console.log(event); // OK: fewer params allowed
// const bad: Handler = (event, index, extra) => {}; // Error: too many required paramsReal-world example
Passing a simple callback like `(item) => ...` where an array method expects `(item, index, array) => ...`.
Likely follow-ups
- Why does this asymmetry exist — why can a function with FEWER parameters satisfy a type expecting MORE?
Related topics