Sub topic 10
Comparing Function Types
Prerequisites and the basic question
This chapter assumes you know TypeScript functions, interfaces, and type annotations. It also assumes you have seen compiler errors such as “not assignable to parameter of type.”
When TypeScript compares two function types, it asks whether a value of the source type can safely be used where the target type is expected:
type Source = (value: Dog) => Animal;
type Target = (value: Animal) => Dog;The source and target are checked separately for parameters and return values. A function must accept every argument the target might provide, and its result must satisfy what the target promises.
Parameter count
A function that declares fewer required parameters can be assigned to a function type that supplies more parameters. The source function can safely ignore extra arguments.
const fewer: (a: number, b: number) => void = (a) => {
console.log(a);
};
// @ts-expect-error The source function requires an argument that the target might not supply.
const more: (a: number) => void = (a, b: number) => {
console.log(a + b);
};This rule matters for callbacks. An array method may call a callback with several arguments, but your callback can use only the ones it needs.
Optional and rest parameters can change the details, but the safety rule remains: the target must never call the source in a way the source cannot handle.
Parameter types
With strictFunctionTypes, function parameters are checked contravariantly. In practice, a callback that accepts a broad type can be used where a callback for a narrower type is required.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
const handleAnimal = (animal: Animal): void => {
console.log(animal.name);
};
const handleDog: (dog: Dog) => void = handleAnimal;
// @ts-expect-error A function requiring Dog cannot handle every Animal.
const unsafe: (animal: Animal) => void = (dog: Dog) => {
dog.bark();
};The assignment to handleDog is safe because every Dog is an Animal. The reverse assignment is unsafe because an Animal might not have bark.
Return types
Return types work in the opposite direction. The source may return a more specific type than the target requests.
| Source return | Target return | Assignment |
|---|---|---|
| `Dog` | `Animal` | Allowed |
| `Animal` | `Dog` | Rejected |
const makeDog = (): Dog => ({
name: "Rex",
bark: () => console.log("woof"),
});
const makeAnimal: () => Animal = makeDog;
// @ts-expect-error An Animal result is not guaranteed to be a Dog.
const makeDogOnly: () => Dog = (): Animal => ({ name: "Milo" });A function returning a value can also be used where a void return is expected. The caller is allowed to ignore that value.
Exercise
Can (dog: Dog) => void be assigned to (animal: Animal) => void under strictFunctionTypes?
Show answer
No. The target may pass an Animal that is not a Dog, so the source function could call a missing bark method.