Lesson 6 / 1250%

Lesson 6

Functions

22 min

Type parameters and return values, default values, callbacks, void and never.

What is a typed function?

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.

Typing parameters and the return value

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.

functions.ts
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
Screenshot of VS Code showing a type error on a function call with a missing argument.

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

Arrow functions are typed in exactly the same way: the parameters in parentheses are annotated, and the return type goes right before the arrow.

arrows.ts
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 Lea

Optional parameters and default values

A 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.

optional.ts
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);           // 120

Warning

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.

Returning several values

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.

multiple.ts
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.

When the result may be missing

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.

missing.ts
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.

The void and never types

  • void: the function returns nothing (for example a function that just displays a message).
  • never: the function never ends normally (it always throws an error or loops forever).
void_never.ts
function log(message: string): void {
  console.log(message);
}

function fail(message: string): never {
  throw new Error(message);
}

Typing a function passed as a parameter

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.

callback.ts
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]
Screenshot of VS Code showing the type of a function passed as a parameter.

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.

Rest parameters

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.

rest.ts
function sum(...numbers: number[]): number {
  return numbers.reduce((total, n) => total + n, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

Good 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).

Common mistakes

Here are the three errors TypeScript will report most often with functions, and how to fix them.

  • Wrong number of arguments: add the missing argument, or make the parameter optional with ? if its absence makes sense.
  • Wrong argument type: convert the value (for example with Number) before the call, instead of working around the error.
  • Inconsistent return: check that every branch of the function returns a value of the announced type.

Summary

  • A signature describes the types of the parameters and of the return value.
  • ? makes a parameter optional; a default value makes it optional with an inferred type.
  • void means "returns nothing", never means "never finishes".
  • The type of a function passed as a parameter is described with an arrow.
  • Rest parameters (...) form a typed array.

Exercise

Write a function 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

Write a function filterNumbers that takes an array of numbers and a test function (n: number) => boolean, and returns the elements that pass the test.