Sub topic 7
Comparing Function Types in TypeScript
This chapter assumes you know basic TypeScript annotations, interfaces, type aliases, and JavaScript functions. The same structural idea used for objects also applies to function types, but function parameters and return values follow different compatibility rules.
A function's shape
A function type describes:
- The number and types of parameters it can receive.
- The type of value it returns.
Two function types are compatible when a function assigned to one type can safely be used wherever the other type is expected.
Parameter compatibility
A function that ignores an argument can be used where a function receiving that argument is expected. This is useful for callbacks.
interface EventData {
message: string;
}
type EventHandler = (event: EventData) => void;
const ignoresEvent: EventHandler = () => {
console.log("An event happened");
};
const usesEvent: EventHandler = (event) => {
console.log(event.message);
};
function register(handler: EventHandler): void {
handler({ message: "Saved" });
}
register(ignoresEvent);
register(usesEvent);ignoresEvent declares no parameters, but register can still call it with one argument. JavaScript safely ignores extra arguments.
The reverse is unsafe. A function that requires two parameters cannot be used where callers are only guaranteed to provide one. TypeScript rejects that assignment.
Parameter direction and `strictFunctionTypes`
For function parameters, the assigned function generally must accept at least the range of values that the target function might provide. A wider parameter type is therefore safer than a narrower one.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
type DogHandler = (dog: Dog) => void;
type AnimalHandler = (animal: Animal) => void;
const animalHandler: AnimalHandler = (animal) => {
console.log(animal.name);
};
const dogHandler: DogHandler = (dog) => {
dog.bark();
};
const canHandleDog: DogHandler = animalHandler;
// @ts-expect-error A Dog handler cannot handle every Animal.
const cannotHandleEveryAnimal: AnimalHandler = dogHandler;
canHandleDog({ name: "Rex", bark() {} });The AnimalHandler is assignable to DogHandler because every Dog is an Animal. The handler only uses the common name property, so it works for dogs.
The DogHandler is not assignable to AnimalHandler. The caller might pass a cat, which has no bark method. Enable "strict": true in tsconfig.json; this includes strictFunctionTypes and catches this mistake.
Return type compatibility
Return types work in the more familiar direction. A function may return a more specific type when the caller expects a more general type.
type MakeAnimal = () => Animal;
type MakeDog = () => Dog;
const makeDog: MakeDog = () => ({
name: "Rex",
bark() {},
});
const makeAnimal: MakeAnimal = makeDog;
// @ts-expect-error An Animal might not be a Dog.
const cannotMakeDog: MakeDog = () => ({ name: "Milo" });
console.log(makeAnimal().name);makeDog fits MakeAnimal because every returned Dog is also an Animal. The reverse assignment would allow callers to invoke bark on a value that might not have that method.
| Part of function | Safe assignment rule |
|---|---|
| Parameters | The source accepts values at least as broadly as the target may provide |
| Return value | The source returns a type assignable to the target's return type |
Common callback error
A callback often receives a value that can be absent or can have several forms. Do not narrow its parameter unless the API guarantees that narrower value.
Exercise
Is (animal: Animal) => void assignable to (dog: Dog) => void, and why?
Show answer
Yes. Every Dog is an Animal, and the function only requires the Animal members that every Dog has.