Parameters and Return Type

Just like any variable, you can assign a type to the function parameters and return value:

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

The return type can usually be inferred, but writing it down documents the function and catches a wrong return early.

Functions need not have a return value and for such functions, use void as return type.

function logName(name: string): void {
  console.log(name);
}

Optional, Default and Rest Parameters

// Optional: may be left out (type is string | undefined)
function greet(name: string, title?: string): string {
  return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}

// Default: type is inferred from the default value
function repeat(text: string, times = 2): string {
  return text.repeat(times);
}

// Rest: any number of arguments, collected into an array
function sum(...numbers: number[]): number {
  return numbers.reduce((total, n) => total + n, 0);
}

Optional and default parameters must come after the required ones.

Arrow Functions

// "Fat arrow" syntax
const square = (n: number): number => {
  return n * n;
};

// "Fat arrow" syntax with return type inferred
const square2 = (n: number) => {
  return n * n;
};

// "Fat arrow" syntax with return type inferred and no return keyword (braceless).
const square3 = (n: number) => n * n;

Function Type Expressions

Describe the type of a function itself, e.g. for a callback parameter:

type Greet = (name: string) => string;

const sayHello: Greet = (name) => `Hello, ${name}`;

function runCallback(callback: (value: number) => void) {
  callback(42);
}

When a function is assigned to a typed variable, its parameters get their types from that type (here name is a string without an annotation).

Interface for Functions

An interface can describe a function too (a call signature):

interface Greet {
  (name: string): string;
}

const sayHello: Greet = (name) => {
  return `Hello, ${name}`;
};

Overloads

Overloads describe a function that can be called in several different ways. Write the signatures first, then one implementation that handles all of them:

function format(value: string): string;
function format(value: number, decimals: number): string;
function format(value: string | number, decimals?: number): string {
  return typeof value === "number" ? value.toFixed(decimals) : value.trim();
}

format(" hi "); // OK
format(3.14159, 2); // OK
format(3.14159); // Error: no signature takes a number on its own
Overloads are rarely needed. A union parameter (value: string | number) is usually simpler.

Generic functions are covered in Generics.