Lesson 6
22 min
Type parameters and return values, default values, callbacks, void and never.
Definition
A function is a named, reusable block of code that receives values (the parameters) and can return another one (the return value). Its signature is the description of the types of its parameters and of its return value: it is what allows TypeScript to check every call.
Functions are where most errors creep in: you call a function with the arguments in the wrong order, with a text instead of a number, or you forget an argument. By typing the signature, TypeScript catches all of these mistakes before the program even runs.
In a function, you type each parameter and, after the parentheses, the return value. These annotations make up the function's "contract": what it expects and what it promises to return.
function add(a: number, b: number): number {
return a + b;
}
add(2, 3); // 5
add(2, "3"); // Error: string is not assignable to number
add(2); // Error: an argument is missing
The return type can be inferred, but writing it explicitly is a good habit: TypeScript then reports an error if the function returns something other than expected.
Also note that TypeScript checks the number of arguments: in plain JavaScript, add(2) would simply have given NaN, an absurd result with no error message at all. Here, the error appears right away in the editor.
Arrow functions are typed in exactly the same way: the parameters in parentheses are annotated, and the return type goes right before the arrow.
const multiply = (a: number, b: number): number => a * b;
const greet = (firstName: string): string => "Hello " + firstName;
console.log(multiply(4, 5)); // 20
console.log(greet("Lea")); // Hello LeaA parameter followed by ? is optional: its value is then undefined if it is omitted. You can also provide a default value, in which case the type is inferred.
function introduce(name: string, title?: string): string {
if (title) {
return title + " " + name;
}
return name;
}
function priceWithTax(price: number, tax = 0.2): number {
return price * (1 + tax);
}
introduce("Smith"); // "Smith"
introduce("Smith", "Dr"); // "Dr Smith"
priceWithTax(100); // 120Warning
Optional parameters must always be placed after the required parameters.
In introduce, the if (title) test is essential: since title can be undefined, TypeScript forbids using it as a text until you have checked that it is present. The default value of priceWithTax avoids this work: the tax parameter is always a number inside the function.
A function only returns a single value, but that value can be a tuple or an object that groups several. A tuple suits two or three values whose order is obvious; an object is more readable as soon as the values have different roles.
function minMax(values: number[]): [number, number] {
return [Math.min(...values), Math.max(...values)];
}
function statistics(values: number[]): { sum: number; average: number } {
const sum = values.reduce((t, n) => t + n, 0);
return { sum, average: sum / values.length };
}
const [small, large] = minMax([4, 9, 2]);
const { average } = statistics([4, 9, 2]);In both cases, destructuring directly gives a name to each received value, and TypeScript knows the type of each one: here, small, large and average are all numbers.
Some functions don't always find what they are looking for. Rather than returning an invented value, you declare that the return can be undefined using a union. The caller is then required to handle the missing case before using the result.
function findFirstName(firstNames: string[], start: string): string | undefined {
return firstNames.find((p) => p.startsWith(start));
}
const result = findFirstName(["Lea", "Tom"], "T");
// result.toUpperCase(); // Error: result may be undefined
if (result !== undefined) {
console.log(result.toUpperCase()); // OK
}This check-before-use technique is the same one we saw with unknown: until the test has been done, TypeScript refuses the risky operation. This is what prevents the infamous "cannot read properties of undefined" crash.
function log(message: string): void {
console.log(message);
}
function fail(message: string): never {
throw new Error(message);
}You can also describe the type of a function itself, which is very useful for callbacks: you indicate the expected parameters and the return type with an arrow.
function apply(values: number[], transform: (n: number) => number): number[] {
return values.map(transform);
}
const doubled = apply([1, 2, 3], (n) => n * 2);
console.log(doubled); // [2, 4, 6]
In the call apply([1, 2, 3], (n) => n * 2), you don't need to annotate n: TypeScript knows the expected shape of the function passed in and deduces that n is a number. This is called contextual typing.
When a function must accept a variable number of arguments, you use a rest parameter, introduced by three dots. It is always of array type and must be the last parameter.
function sum(...numbers: number[]): number {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4)); // 10Good to know
A function declared void can perfectly well contain statements, but it must not return a usable value. Don't confuse void (nothing is returned) with never (the function never finishes).
Here are the three errors TypeScript will report most often with functions, and how to fix them.
? if its absence makes sense.? makes a parameter optional; a default value makes it optional with an inferred type.void means "returns nothing", never means "never finishes"....) form a typed array.Exercise
calculateFinalPrice(price, discount?) that applies a percentage discount if one is provided, and returns the final price. Carefully type the parameters and the return value.Going further
filterNumbers that takes an array of numbers and a test function (n: number) => boolean, and returns the elements that pass the test.