Sub topic 13
When one function type is assignable to another
This chapter assumes you can write function type expressions such as (a: string) => number. It also assumes you know what void and never mean as return types, and that you have used strict mode in tsconfig.json. Here you will learn the rules the compiler applies when you assign one function to a variable, parameter, or property of another function type.
Assignability as a substitution test
A value of type S is assignable to type T when you can safely use it anywhere a T is expected. For functions, "safely" means two things:
- Every call a caller can make to a
Tmust also be valid for theS. - Every result the
Sproduces must be something the caller ofTcan handle.
So the check has two parts: the parameters, and the return type. The compiler compares them separately.
The diagram below summarizes the checks. A reader of the source will find it in the next block.
Parameter count: fewer is fine, more is not
A source function may declare fewer parameters than the target. The caller passes extra arguments and the function ignores them. JavaScript already works this way, so the type system allows it.
type Handler = (event: string, index: number) => void;
const onlyEvent: Handler = (event) => console.log(event); // ok
const noParams: Handler = () => console.log("fired"); // ok
// const tooMany: Handler = (event, index, extra: boolean) => {};
// error: Target signature provides too few arguments. Expected 3 or more, but got 2.The reverse fails. A function that needs a third argument cannot stand in for a type whose callers supply only two.
The `map(parseInt)` trap
This rule explains a well-known bug that compiles cleanly. Array.prototype.map calls its callback with (value, index, array). parseInt has the signature (string: string, radix?: number) => number, so it needs at most two arguments and is assignable.
const parsed = ["1", "2", "3"].map(parseInt);
console.log(parsed); // [1, NaN, NaN]The index is passed as the radix. The compiler accepted the call because the types line up, even though the behavior is wrong. When you pass an existing function as a callback, check what arguments the caller supplies. Wrapping it, as in .map(s => parseInt(s, 10)), removes the doubt.
Optional and rest parameters
Optionality is compared by whether the parameter must be supplied.
- A source with an optional parameter can be assigned to a target where that parameter is required, or absent.
- A source with a required parameter cannot be assigned to a target that treats it as optional, if the target's callers may omit it. Under
strictNullChecksthe optional parameter's type includesundefined, so the source would receiveundefinedwhere it expects a value.
type Log = (message: string, level?: number) => void;
const strict: (message: string, level: number) => void = (m, l) => {};
// const bad: Log = strict;
// error: 'number | undefined' is not assignable to 'number'
const lenient: Log = (message) => console.log(message); // okRest parameters behave like an unlimited run of parameters of the same type. A target of (...args: number[]) => void accepts a source of (a: number, b: number) => void, because the compiler does not know how many arguments the caller supplies and treats the source's parameters as matching the rest elements.
Return types are covariant
Return types are checked in the direction you would expect. The source's return type must be assignable to the target's return type. A function that returns more specific data can stand in for one that returns less.
type MakeNamed = () => { name: string };
const makeDog = () => ({ name: "Rex", breed: "Labrador" });
const make: MakeNamed = makeDog; // ok: the extra 'breed' is harmlessThis is called covariance: the relationship between the function types follows the relationship between the return types. The excess property check you know from object literals does not apply here, because the returned object is not a fresh literal at the point of assignment.
`void` and `never` as return types
void has a special rule in function types. When the target returns void, the source may return anything, and callers must not use the result.
const handlers: Array<() => void> = [];
handlers.push(() => 42); // allowed
function declared(): void {
// return 42; // error: a function declaration with a void annotation cannot return a value
}The leniency applies only when void appears in the target function type. A function you declare yourself with a void annotation is still checked strictly. This is why arr.forEach(item => results.push(item)) compiles: push returns a number, and forEach expects a callback returning void.
never is assignable to every type, so a function that always throws fits any return type.
function fail(message: string): never {
throw new Error(message);
}
const getName: () => string = () => fail("no name"); // okThe reverse is not true. A () => string is not assignable to () => never, because the caller would assume the function never returns.
Parameter types are contravariant
Parameters work in the opposite direction from return types. Think of a function that accepts a broad type as one that can handle every narrower value too. So the target's parameter type must be assignable to the source's parameter type.
type Animal = { name: string };
type Dog = Animal & { breed: string };
type AnimalHandler = (a: Animal) => void;
type DogHandler = (d: Dog) => void;
const handleAnimal: AnimalHandler = (a) => console.log(a.name);
const handleDog: DogHandler = (d) => console.log(d.breed);
const ok: DogHandler = handleAnimal; // ok: any Dog is also an Animal
// const bad: AnimalHandler = handleDog;
// error under strictFunctionTypes: a caller could pass an Animal with no 'breed'This is contravariance: the relationship between function types runs opposite to the relationship between parameter types. The second assignment would be unsafe. A caller holding an AnimalHandler may pass any animal, and handleDog would read d.breed on a value that has none.
| Position | Direction | Source type must be | Example |
|---|---|---|---|
| Return type | Covariant | Same as, or narrower than, the target | `() => Dog` fits `() => Animal` |
| Parameter type | Contravariant | Same as, or wider than, the target | `(a: Animal) => void` fits `(d: Dog) => void` |
| Parameter count | Fewer is allowed | At most as many required as the target supplies | `() => void` fits `(x: number) => void` |
| `void` target return | Any return allowed | Anything | `() => number` fits `() => void` |
`strictFunctionTypes` and method bivariance
The contravariant check is applied only when strictFunctionTypes is on. It is part of the strict flag. With it off, parameters are compared bivariantly: the assignment succeeds if the parameter types are assignable in either direction. That is the unsound behavior the flag was added to remove.
Even with the flag on, the strict check applies to function type expressions and function-typed properties. It does not apply to members declared with method syntax. Methods stay bivariant, which keeps common patterns such as Array<T> assignable to Array<U> for related types.
interface MethodStyle {
handle(a: Animal): void; // method syntax: bivariant
}
interface PropertyStyle {
handle: (a: Animal) => void; // function-typed property: contravariant
}
const m: MethodStyle = { handle: handleDog }; // allowed, though unsafe
// const p: PropertyStyle = { handle: handleDog }; // error under strictFunctionTypesThe two interfaces describe the same call shape but are checked differently. If you want the stricter check on a member, declare it as a property with a function type.
Reading assignability errors
Error messages for functions are long, because the compiler reports the first failing step and then explains it. Read them with the table above in mind.
- "Target signature provides too few arguments" means the source requires more parameters than the target supplies.
- "Types of parameters 'x' and 'y' are incompatible" means the contravariant check failed. Look at which type is narrower.
- "Type 'X' is not assignable to type 'Y'" under a return type means the covariant check failed.
When the message is hard to follow, write the target type as a named alias and assign the source to a variable of that type. The error then points to one line.
Putting the rules to work
The rules explain several everyday decisions:
- You can pass a callback that ignores trailing arguments, such as
onClick={() => save()}, because fewer parameters are allowed. - When you write a library function that accepts a callback, type its parameters as the narrowest values you actually pass. Callers with wider parameter types will still be accepted.
- When you write a function that returns an object, expect callers to treat it as any wider type that it satisfies.
- When you store handlers for different event types in one collection, a handler for a narrow event type will not fit a slot for a wide one. Either widen the slot's type, or keep separate collections for each event type.
Exercise
Given type Animal = { name: string }, type Dog = Animal & { breed: string }, and const f = (d: Dog): Animal => ({ name: d.name }), which of these assignments compile under strict? (a) const x: (d: Dog) => Animal = f; (b) const y: (a: Animal) => Animal = f; (c) const z: (d: Dog) => { name: string; age: number } = f; (d) const w: (d: Dog) => void = f;
Show answer
(a) and (d) compile. (a) matches exactly. (d) is allowed because a target returning void accepts any source return type. (b) fails: the target parameter Animal is not assignable to the source parameter Dog, so the contravariant check fails. (c) fails: the source returns Animal, which lacks the required age property, so the covariant return check fails.
Exercise
The following code compiles. Explain why, and say what the output is. console.log(["10", "10", "10"].map(parseInt));
Show answer
parseInt has the type (string: string, radix?: number) => number. It needs at most two arguments, and map supplies three (value, index, array), so it is assignable because functions with fewer parameters are allowed. At runtime map passes the index as the radix, so the output is [10, NaN, 2]. This is parseInt("10", 0) (radix 0 means decimal), parseInt("10", 1) (invalid radix), and parseInt("10", 2) (binary 10).