Sub topic 10
Comparing function types
This chapter covers how TypeScript decides whether one function type can be used where another is expected. It assumes you know interfaces, type aliases and arrow functions, and that you've read the earlier chapters on the source/target view of assignability and on structural typing. The next chapters cover variance in depth. Here the focus is parameter count, return types, and a few rules that surprise people.
The same question, asked of functions
Assignability asks whether a source type can be used where a target type is expected. For functions, the target is a signature that callers will use. The source is the function you supply. The question becomes: if every caller follows the target's signature, will the source function work safely?
That one question explains the two main checks.
- Parameters: the source must not demand more than the target's callers provide.
- Return type: the source must give back at least what the target's callers expect.
Parameter count: fewer is fine
A function that needs fewer parameters can stand in for one that supplies more. The extra arguments are ignored, which is safe. The reverse fails, because the source would read an argument that nobody passes.
const fewer: (a: number, b: number) => void = (a) => {}; // OK: ignoring a parameter is safe
const more: (a: number) => void = (a, b: number) => {}; // Error: the source requires a second argumentThis is why callbacks are short in everyday code. Array.prototype.forEach calls its callback with a value, an index and the array. You declare only what you need.
const nums = [10, 20, 30];
nums.forEach((n) => {
console.log(n);
});
nums.forEach(() => {
console.log("tick");
});Both calls compile. The callback type expects up to three parameters, and each source needs no more than that.
Optional and rest parameters
Optional parameters in the source do not count as demands. A source with a required parameter beyond what the target supplies fails. A source with an optional one passes. A rest parameter in the target means callers may pass any number of arguments.
const optionalOk: (a: number) => void = (a: number, b?: number) => {}; // OK
const requiredBad: (a: number) => void = (a: number, b: number) => {}; // Error
const anyCount: (...args: number[]) => void = (a: number, b: number) => {}; // OKOptional parameters in the target are also treated leniently. TypeScript does not insist that a source accept undefined for them.
Return types are covariant
A function type's return type is covariant. A source that returns a more specific type can replace a target that promises a less specific one. Callers get at least what they were promised.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
const getDog = (): Dog => ({ name: "Rex", bark() {} });
const getAnimal: () => Animal = getDog; // OK: a Dog is an Animal
const makeAnimal = (): Animal => ({ name: "Generic" });
const makeDog: () => Dog = makeAnimal; // Error: Animal lacks 'bark'The check on return types is the ordinary assignability check from the source's return type to the target's return type.
Parameter types go the other way
Parameter types are compared in the opposite direction. The target's parameter type must be assignable to the source's parameter type, because the source will receive whatever callers pass.
const accepts: (x: string) => void = (x: string | number) => {}; // OK: source handles more than needed
const rejects: (x: string | number) => void = (x: string) => {}; // Error under strictFunctionTypesThis direction is called contravariance. The following chapters cover it, along with the strictFunctionTypes flag and method bivariance, so treat this section as a preview.
The void return special case
A target with return type void accepts a source that returns any type. The returned value is simply ignored.
type Callback = () => void;
const cb: Callback = () => 42; // OK
const ids: number[] = [];
[1, 2, 3].forEach((n) => ids.push(n)); // OK: push returns a number, forEach ignores itThis rule exists so that expression-bodied arrow functions can be used as callbacks without wrapping them in braces.
Two limits apply:
- The rule applies to function types, not to declarations. A function written with an explicit
: voidreturn annotation that returns a value is an error. - A caller of a
() => voidfunction cannot use the result. The type says nothing useful about it, even if the runtime function returns 42.
function declared(): void {
return 42; // Error: Type 'number' is not assignable to type 'void'
}How the checks fit together
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Error: source requires a second argument | Source has more required parameters than the target provides | Make the parameter optional, or change the target type to supply it |
| Error: `Animal` is missing a property of `Dog` in a return position | Source returns a wider type than the target promises | Return the narrower type, or widen the target |
| A callback's return value seems ignored | Target returns `void` | Declare the real return type on the target if callers need the value |
| Error: a `: void` function returns a value | The void special case applies only to function types | Remove the return value, or change the annotation |
Practical advice
- Write callback parameter lists with only the parameters you use. The assignability rules make this free.
- Declare the precise return type on target signatures when callers need the result. Use
voidonly when the result must be ignored. - If you see an unexpected parameter error, ask first whether the source demands more than the target provides.
Exercise
Given type Handler = (event: string, index: number) => void;, which of these assignments compile: (1) const h1: Handler = (e) => {}; (2) const h2: Handler = (e, i, extra: boolean) => {}; (3) const h3: Handler = (e, i) => e.length;? Explain each.
Show answer
(1) Compiles. The source needs fewer parameters than the target supplies. (2) Does not compile. The source has a third required parameter that callers of Handler never pass. (3) Compiles. The target returns void, so the source's number return value is ignored.
Exercise
Why does const f: () => Dog = (): Animal => ({ name: "x" }); fail while the reverse assignment succeeds? Use the terms source and target.
Show answer
Return types are covariant. The source's return type must be assignable to the target's return type. In the failing case, Animal (source return) is not assignable to Dog (target return) because it lacks bark. In the reverse case, Dog is assignable to Animal, so it succeeds.