Sub topic 13
When One Function Type Is Assignable to Another
Assume you know JavaScript functions, TypeScript parameters, object types, unions, and how to run tsc. This chapter explains how TypeScript decides whether one function can be used where another function type is expected.
The basic rule
A function type describes the arguments a function accepts and the value it returns:
type Formatter = (value: string) => string;
const upper: Formatter = (value) => value.toUpperCase();The function assigned to Formatter must safely handle every call allowed by Formatter. Its return value must also be usable wherever the declared return type is expected.
The main rules are:
| Part of a function | Assignability rule |
|---|---|
| Parameters | The assigned function must accept the required inputs safely |
| Return value | The assigned function must return a compatible value |
| Optional parameters | A required parameter cannot replace an optional one |
| Extra parameters | A function may often ignore extra arguments |
Parameter types and variance
Consider these types:
type Animal = { name: string };
type Dog = Animal & { bark(): void };
type AnimalHandler = (animal: Animal) => void;
type DogHandler = (dog: Dog) => void;
const handleAnimal: AnimalHandler = (animal) => {
console.log(animal.name);
};
const handleDog: DogHandler = (dog) => {
dog.bark();
};
const safeHandler: AnimalHandler = handleAnimal;
// const unsafeHandler: AnimalHandler = handleDog;A variable of type AnimalHandler might receive a plain Animal that is not a Dog. Assigning handleDog would therefore be unsafe because it always calls bark.
With strictFunctionTypes enabled, TypeScript checks ordinary function parameters contravariantly. In practice, a function that accepts a broader type can be used where a function accepting a narrower type is needed. The reverse is rejected.
Methods in object types have some historical bivariance behavior, so callback properties are usually safer when written as function-valued properties:
type SafeHandlers = {
onAnimal: (animal: Animal) => void;
};Return types
Return types are checked in the opposite direction. A function returning a more specific value can be assigned to a function returning a more general value:
type AnimalFactory = () => Animal;
const makeDog = (): Dog => ({
name: "Rex",
bark() {
console.log("woof");
}
});
const makeAnimal: AnimalFactory = makeDog;Every Dog is an Animal, so callers can safely treat the result as an Animal. A function returning only Animal cannot replace a function promised to return Dog, because the result might not have bark.
Optional and extra parameters
A function with a required parameter cannot replace a function type where callers may omit that parameter:
type OptionalGreeting = (name?: string) => string;
// const invalid: OptionalGreeting = (name: string) => name;The caller is allowed to call invalid() according to OptionalGreeting, but the assigned function requires a string.
The reverse is safe:
const valid: (name: string) => string = (name?: string) => name ?? "Guest";A function that accepts an optional value can handle a required value.
JavaScript often passes extra arguments. TypeScript therefore commonly allows the assigned function to declare fewer parameters than the target function:
const first: (value: string, index: number) => string =
(value) => value.toUpperCase();Checking assignability mentally
Use this process:
- List calls that the target function type permits.
- Check that the assigned function can handle every permitted argument.
- Check that its return value fits the target return type.
- Check optional parameters and
strictFunctionTypes.
Exercise
Can a function of type (dog: Dog) => void safely replace (animal: Animal) => void? Explain why.
Show answer
No. The target type allows a caller to pass any Animal, but the Dog function may call dog-specific members such as bark.