Sub topic 7
Comparing function types
This chapter assumes you know TypeScript function type annotations, arrow functions and callbacks. You should also know that TypeScript decides assignability by shape, as earlier chapters showed. Here the same shape rule is applied to functions. For a function, the shape is its parameters and its return type.
What "shape" means for a function
A function type has two parts the checker cares about: the list of parameters and the return type. Names do not count, and neither does where the function was declared. The check asks one question: can a value of the source type be called in every way the target type promises?
Take this target type:
type Handler = (event: string) => void;Any function assigned to a Handler will be called with one string argument. Its result is ignored. So the source function must work when it receives one string, and it may return anything. The rest of this chapter follows from that reading.
Parameter count: fewer is fine, more is not
A function that declares fewer parameters than the target supplies is assignable. It simply ignores the extra arguments. A function that requires more parameters than the target supplies is not assignable, because nobody will pass those arguments.
type Handler = (event: string) => void;
const ignoresArgs: Handler = () => {}; // OK: fewer parameters are allowed
const needsMore: Handler = (event: string, extra: number) => {};
// Error: the target supplies only one argumentThis rule is why callbacks in JavaScript APIs feel natural. Array.prototype.forEach calls its callback with the value, the index and the array. You can write a callback that uses any prefix of those, including none:
const numbers = [10, 20, 30];
numbers.forEach((n) => console.log(n));
numbers.forEach((n, i) => console.log(i, n));
numbers.forEach(() => console.log("tick"));All three calls compile. Only a callback that demands a fourth required parameter would be rejected.
Optional and rest parameters
Extra parameters are allowed when the source marks them optional, because a caller who omits them is still valid. A rest parameter in the source can absorb any number of arguments from the target.
type Pair = (a: number, b: number) => number;
const sum: Pair = (...nums: number[]) =>
nums.reduce((total, n) => total + n, 0);
const extraOptional: (a: number) => void = (a: number, b?: string) => {};
console.log(sum(2, 3)); // 5
extraOptional(1);Both assignments compile. The first works because a rest parameter of type number[] accepts the two numbers the target passes. The second works because b can be left out.
Parameter names do not matter
Only the position and type of each parameter are compared. These two types are interchangeable:
type ByName = (userName: string) => number;
type ByOtherName = (label: string) => number;
const lengthOf: ByName = (s) => s.length;
const same: ByOtherName = lengthOf; // OK: names are documentation onlyNames still help readers and editor tooltips, so choose them with care. The checker ignores them.
Return types: the source may return more
For return types, the source must return something the target's callers can use. That means the source's return type must be assignable to the target's return type. A function that returns a more specific type is therefore fine, and one that returns a less specific type is not.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
const makeDog: () => Dog = () => ({ name: "Rex", bark() {} });
const makeAnimal: () => Animal = makeDog; // OK: every Dog is an Animal
const backToDog: () => Dog = makeAnimal;
// Error: Property 'bark' is missing in type 'Animal' but required in type 'Dog'.This is the same object-shape rule from earlier chapters, applied to the value that comes out of the call. Return types are compared in the same direction as ordinary assignment. Type theorists call this covariance, and you can use that word when reading other sources.
The void exception
A target that returns void accepts a source that returns anything. The caller of a void function promises to ignore the result, so a returned value cannot cause harm.
type Callback = () => void;
const cb: Callback = () => 42; // OK: the number is ignored by callers
const items: string[] = [];
const addItem: (s: string) => void = (s) => items.push(s);
// push returns a number, but the target says void, so this is fine
addItem("first");
console.log(items); // ["first"]Without this rule, the one-line addItem arrow would fail, and you would need braces just to discard a value.
The exception applies to assigning a function to a function type. It does not apply to a function that you declare with an explicit void return annotation:
function declared(): void {
return 42;
// Error: Type 'number' is not assignable to type 'void'.
}Also, the type of the call result stays void. In the earlier example, cb() has type void, even though the actual runtime value is 42. Do not rely on the value.
Parameter types: the source must accept what the target passes
The source parameter types must accept every value the target will pass. If the target passes a Dog, a source that accepts any Animal is safe, because every Dog is an Animal. A source that demands a Dog is unsafe when the target might pass any Animal.
// tsconfig: "strict": true (includes strictFunctionTypes)
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
let feedDog: (d: Dog) => void = (a: Animal) => {}; // OK
let feedAnimal: (a: Animal) => void = (d: Dog) => {};
// Error under strictFunctionTypes: parameter types are checked contravariantlyParameters flow in the opposite direction from return types. Return types may become more specific, and parameter types may become more general. This is called contravariance. The chapter on parameter variance and strictFunctionTypes covers the details and the flag's escape hatches. For now, remember the rule of thumb: a function that accepts more can stand in for one that accepts less.
The summary below puts all the rules in one place:
| Part of the signature | Source may be... | Example |
|---|---|---|
| Parameter count | Fewer required parameters than the target supplies | `() => {}` for `(e: string) => void` |
| Extra parameters | Optional, or a rest parameter | `(a: number, b?: string) => void` for `(a: number) => void` |
| Parameter types | Wider (accepts more) | `(a: Animal) => void` for `(d: Dog) => void` |
| Return type | Narrower (returns more specific) | `() => Dog` for `() => Animal` |
| Return type, target `void` | Anything | `() => 42` for `() => void` |
| Parameter names | Different | `(label: string)` for `(userName: string)` |
Methods are checked more loosely
The strict parameter check applies to properties whose type is a function type. Members declared with method syntax are exempt, and their parameters are compared bivariantly, which means either direction passes.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
interface MethodStyle {
handle(a: Animal): void;
}
interface PropertyStyle {
handle: (a: Animal) => void;
}
const dogOnly = (d: Dog) => d.bark();
const m: MethodStyle = { handle: dogOnly }; // OK: method parameters are bivariant
const p: PropertyStyle = { handle: dogOnly };
// Error under strictFunctionTypesThe method case compiles even though dogOnly would crash if it received a plain Animal. TypeScript keeps this leniency because many built-in types, such as arrays and DOM events, are declared with method syntax and rely on it. When you design your own interfaces and want the stricter check, declare callbacks as properties with function types.
Overloads and generics in brief
When the target type has several overload signatures, the source must provide a compatible signature for each one. The checker looks for a matching signature in the source for every target overload. When the source is generic, TypeScript tries to fill in its type parameters from the target so that the comparison can proceed. Both cases follow the same principle: the source must be usable in every way the target promises.
Common mistakes
- Expecting extra parameters to be allowed. A source needing more required parameters than the target passes is always an error. Make the extra parameter optional, or change the target type.
- Treating
voidas "returns nothing". A() => voidcallback can return a value, and callers must not use it. - Comparing names. Renaming a parameter never fixes or causes an assignability error.
- Reading parameter types in the wrong direction. Remember that a source parameter must be able to accept everything the target will pass in.
- Assuming methods and function properties behave the same. Under
strict, only function-typed properties get the strict parameter check.
Exercise
Given type Mapper = (value: number, index: number) => Animal; and interface Animal { name: string } and interface Dog extends Animal { bark(): void }, which of these are assignable to Mapper under strict? (a) (v: number) => Dog (b) (v: number, i: number, extra: string) => Animal (c) (v: number | string) => Animal (d) (v: number, i: number) => void
Show answer
(a), (c). (a) has fewer parameters, and its return type Dog is assignable to Animal. (c) accepts a wider parameter type than the target passes, and it also has fewer parameters. (b) requires a third parameter that the target never supplies. (d) returns void, which is not assignable to Animal; the void exception only applies when the target returns void.
Exercise
Why does const f: () => void = () => 42; compile, while function g(): void { return 42; } does not?
Show answer
When assigning to a function type whose return type is void, TypeScript accepts any source return type, because callers must ignore the result. A function declared with an explicit void return annotation is checked directly against its own return statements, and 42 is not assignable to void.