TypeScript · Lesson 13 of 42
Function types, callbacks and call signatures
Describe a function with a function type, write callbacks with typed parameters, name function types with aliases and use call signatures.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will be able to type the functions you pass around: callbacks, handlers, comparison functions and more. In JavaScript, functions are values, so TypeScript needs a way to describe a function without writing one. That is a function type.
Function types
A function type looks like an arrow function without a body. It lists the parameters, then =>, then the return type:
type BinaryOperation = (a: number, b: number) => number;
const add: BinaryOperation = (a, b) => a + b;
const multiply: BinaryOperation = (a, b) => a * b;
console.log(add(2, 3), multiply(2, 3));5 6Notice that the arrow functions do not annotate a and b. The variable's type tells the compiler what they are, which is contextual typing at work. The parameter names in a function type, such as a and b above, are only labels for readers; they do not have to match the names in the real function.
A function that does not fit the type is rejected:
type BinaryOperation = (a: number, b: number) => number;
const wrong: BinaryOperation = (a: number, b: string) => a;example.ts(3,7): error TS2322: Type '(a: number, b: string) => number' is not assignable to type 'BinaryOperation'.
Types of parameters 'b' and 'b' are incompatible.
Type 'number' is not assignable to type 'string'.Callbacks
A callback is a function passed to another function. The receiving function declares what kind of callback it accepts by giving the parameter a function type:
function applyTwice(value: number, fn: (n: number) => number): number {
return fn(fn(value));
}
console.log(applyTwice(3, n => n * 2));
console.log(applyTwice(3, n => n + 10));12
23The compiler checks both sides. It checks that applyTwice calls fn with a number and uses the result as a number, and it checks that the callback you pass takes a number and returns one:
function applyTwice(value: number, fn: (n: number) => number): number {
return fn(fn(value));
}
applyTwice(3, n => n.toString());example.ts(5,20): error TS2322: Type 'string' is not assignable to type 'number'.This is also why the array methods you already know are so well typed. map, filter and forEach each describe the callback they accept.
Naming function types
When the same function type appears more than once, give it an alias:
type Predicate = (value: string) => boolean;
function keep(items: string[], test: Predicate): string[] {
return items.filter(test);
}
const isShort: Predicate = word => word.length <= 3;
console.log(keep(["cat", "elephant", "dog"], isShort));[ 'cat', 'dog' ]A name like Predicate also explains the purpose of the function better than a repeated arrow type.
void callbacks may return something
A function type whose return type is void does not force the callback to return nothing. It says the caller will not use the result:
const numbers: number[] = [];
[1, 2, 3].forEach((n): void => {
numbers.push(n * 2);
});
function run(callback: () => void): void {
callback();
}
run(() => numbers.push(99));
console.log(numbers);[ 2, 4, 6, 99 ]In the last call, the callback returns the new array length from push, and that is fine. Without this rule, you could not write the short form of an arrow callback that happens to call something returning a value. The result is simply ignored. Note that this rule applies to function types; a function declared directly with : void that returns a value is still an error.
Call signatures
JavaScript functions are objects, so they can have properties. A call signature describes a callable object, with parentheses in an object type:
type Counter = {
(): number;
count: number;
};
function makeCounter(): Counter {
const fn = (() => ++fn.count) as Counter;
fn.count = 0;
return fn;
}
const next = makeCounter();
next();
next();
console.log(next(), next.count);3 3Call signatures are less common than plain function types. You will see them when typing libraries that expose a function with extra properties attached, such as a function that has a cancel method.
Common mistakes
Typing a callback as Function. The built-in Function type accepts any function and checks nothing. Write the real parameter and return types.
Thinking parameter names in a function type matter. They are labels only. Only the types and the order count.
Expecting void callbacks to stop returning values. They may return anything; the caller ignores it.
Forgetting to annotate the receiving side. The callback is checked against the parameter's type, so that type needs to be precise.
Exercise
Write function mapAll(items: number[], fn: (n: number) => string): string[] and call it with a callback that formats each number. Then pass a callback that returns a number and read the error. Give the callback type an alias called Formatter. Finally, write a function onClick(handler: (event: { x: number; y: number }) => void) and call it with a handler that returns a value.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.