← Back to course: TypeScript from scratch

Functions: parameters and return types

Video coming soon

Functions are where TypeScript gives the most value, because they are the boundary between the parts of your program. A well-placed type on a function works as a contract: it says what it needs and what it returns, and the compiler watches it on every call. This week we study how to type functions completely. Today we start with the essentials: parameter types, the return type and function types.

Parameters and return

Each parameter carries its annotation after the name. The return type goes after the parentheses. Although TypeScript can infer the return, annotating it on exported or public functions is good practice: it documents intent and prevents an internal change from altering the contract unnoticed. If the annotated return does not match what you actually return, you get an error at the return, which is exactly where the problem is.

typescript
function add(a: number, b: number): number {
  return a + b;
}

const multiply = (a: number, b: number): number => a * b;

function isAdult(age: number): boolean {
  return age >= 18;
}

// add(1); // error: Expected 2 arguments, but got 1
// add(1, '2'); // error: Argument of type 'string' is not assignable to 'number'
console.log(add(2, 3), multiply(4, 5), isAdult(20));

One detail that surprises people coming from JavaScript: TypeScript checks the number of arguments. In JavaScript you can call add(1) and get NaN without any complaint; in TypeScript it is a compile error. Passing fewer or more arguments is always an error, unless the parameter is optional, which we will see in the next lesson.

void and functions that return nothing

When a function only produces an effect, such as printing to the console or saving a piece of data, its return is annotated as void. It means you do not expect to use the returned value. Do not confuse it with never: a void function finishes normally and returns undefined, while a never function never finishes, because it throws an error or enters an infinite loop.

Function types

Functions are also values, so they have their own type. It is written with an arrow: (a: number, b: number) => number describes any function that takes two numbers and returns a number. The parameter names in the type are only documentation; they do not have to match those of the real function. With a type alias you can name it and reuse it in variables, parameters and properties.

typescript
type BinaryOperation = (a: number, b: number) => number;

const subtract: BinaryOperation = (x, y) => x - y; // x and y inferred as number

function logMessage(message: string): void {
  console.log('[log] ' + message);
}

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

function calculate(op: BinaryOperation, a: number, b: number): number {
  return op(a, b);
}

logMessage('start');
console.log(calculate(subtract, 10, 4)); // 6

A final recommendation: do not repeat the return type on small private functions if inference deduces it unambiguously, but do on exported ones. And remember that arrow functions assigned to a constant can annotate the type in two ways: on the parameters and return, or on the variable with a function alias. Choose one and be consistent. Both are correct; what matters is that whoever reads your code sees at a glance what goes in and what comes out.

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →