All academies
Roadmap/Fundamentals

Level 4

Functions

Learn to type function parameters and return values, use optional and default parameters, write arrow functions, and understand how void and function types work in TypeScript.

20 min read + quiz

Typing Parameters and Return Values

Functions are where TypeScript earns its keep, because a function signature is a contract between the caller and the implementation. Parameters are annotated after their names, and the return type comes after the parameter list. TypeScript checks both directions: callers must pass matching arguments, and the body must actually return the declared type.

Return types can usually be inferred from your return statements, and many teams omit them for short functions. But writing them explicitly on exported or public functions is good practice: the annotation documents intent, produces errors at the function (where the bug is) rather than at distant call sites, and prevents accidental changes to your public contract when you refactor the body.

Unlike JavaScript, TypeScript checks arity: calling a two-parameter function with one or three arguments is a compile error. In JavaScript, missing arguments silently become undefined and extras are silently ignored, both classic sources of bugs.

function applyDiscount(price: number, percent: number): number {
  return price - price * (percent / 100);
}

applyDiscount(100, 20);        // 80
// applyDiscount(100);         // Error: Expected 2 arguments, got 1.
// applyDiscount(100, 20, 5);  // Error: Expected 2 arguments, got 3.

// The body is checked against the declared return type too:
// function broken(): number { return "oops"; }  // Error

Parameter types, a return type, and arity checking - the full function contract.

Optional and Default Parameters

Sometimes a parameter is genuinely optional. Marking it with ? (as in 'suffix?: string') tells TypeScript that callers may omit it, and, crucially, that inside the function its type is 'string | undefined'. The compiler then forces you to handle the undefined case before treating it as a string, preventing the classic 'cannot read properties of undefined' crash.

Default parameters ('suffix: string = "!"') go one step further: callers may still omit the argument, but inside the function the value is always a string, because the default fills the gap. Prefer defaults over optionals whenever a sensible fallback exists; they give you optionality for the caller without undefined-handling inside the body.

Two rules to remember: optional parameters must come after required ones (otherwise callers could not skip them), and a parameter cannot be both optional and have a default, since a default already implies the caller can omit it.

function greet(name: string, title?: string): string {
  if (title === undefined) {
    return "Hello, " + name;
  }
  return "Hello, " + title + " " + name;   // title is string here
}

function repeat(text: string, times: number = 2): string {
  return new Array(times + 1).join(text);  // times is always number
}

console.log(greet("Lovelace"));            // Hello, Lovelace
console.log(greet("Lovelace", "Countess")); // Hello, Countess Lovelace
console.log(repeat("ab"));                  // abab

Optional parameters are 'T | undefined' inside the body; defaults keep the type clean.

Arrow Functions and Function Types

Arrow functions are typed exactly like regular functions: annotate the parameters, optionally annotate the return. They shine in callbacks, where TypeScript performs 'contextual typing': when you pass an arrow function to something like Array.map, the compiler already knows the parameter types from map's signature, so you can omit them entirely.

You can also describe a function as a type of its own, using the arrow syntax in type position: '(a: number, b: number) => number' is the type of any function taking two numbers and returning one. This lets you type variables that hold functions, callback parameters, and function-valued object properties.

This is a large part of typed functional programming in TypeScript: functions are values with precise types, and the compiler verifies that every callback you pass matches the shape the receiver expects.

type BinaryOp = (a: number, b: number) => number;

const add: BinaryOp = (a, b) => a + b;       // params inferred
const multiply: BinaryOp = (a, b) => a * b;

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

console.log(calculate(6, 7, add));       // 13
console.log(calculate(6, 7, multiply));  // 42

// Contextual typing: 'n' is known to be number from map's signature
const doubled = [1, 2, 3].map((n) => n * 2);

A function type alias, functions as arguments, and contextual typing in callbacks.

void, undefined, and never

A function that returns nothing useful has the return type 'void'. This is subtly different from returning undefined: void means 'the caller should not use the return value at all'. Logging functions, event handlers, and side-effect helpers are all void.

There is a surprising but deliberate rule: a callback typed as returning void may actually return a value, and TypeScript will not complain. This is why you can write 'numbers.forEach((n) => results.push(n))' even though push returns a number; forEach declares a void callback, meaning 'I promise to ignore whatever you return'.

'never' is stricter still: it is the return type of functions that never return at all, because they always throw or loop forever. You will mostly meet never later, in exhaustiveness checking, where it proves you have handled every case of a union.

function logScore(name: string, score: number): void {
  console.log(name + " scored " + score);
  // no return value - and callers must not use one
}

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

const result = logScore("Ada", 100);
// result has type void - using it is a mistake TypeScript can catch
console.log(typeof result);   // "undefined" at runtime

void marks 'nothing useful returned'; never marks 'this function does not return at all'.

Rest Parameters and Common Pitfalls

Rest parameters collect any number of trailing arguments into an array: '(...values: number[])'. The annotation is an array type, but callers pass the values individually. This is the typed version of JavaScript's arguments object, and vastly nicer to work with.

A pitfall worth knowing: TypeScript compares functions by compatibility, not exact equality. A callback that takes fewer parameters than expected is fine (ignoring arguments is always safe), which is why '(n) => n * 2' is accepted where '(value, index, array) => ...' is expected. The reverse, requiring more parameters than the caller will provide, is an error.

Also beware of losing types at boundaries. If you annotate a parameter as any to silence an error, every operation downstream loses checking too. It is almost always better to fix the actual type mismatch than to hide it.

function sum(...values: number[]): number {
  return values.reduce((total, v) => total + v, 0);
}

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

// Fewer callback params than provided is fine:
const firstLetters = ["alpha", "beta"].map((word) => word[0]);
console.log(firstLetters);     // ["a", "b"]

Rest parameters type variadic functions; callbacks may safely ignore trailing arguments.

Try it yourself

This lesson's example is preloaded in the playground — break it, fix it, extend it.

Open in playground

Check your understanding

Question 1 · Multiple choice

Inside a function body, what is the type of a parameter declared as 'label?: string'?

Question 2 · Predict the output

What does this program print?

function greet(name: string, punctuation: string = "!"): string {
  return "Hi " + name + punctuation;
}

console.log(greet("Ada"));
console.log(greet("Ada", "?"));

Question 3 · Find the error

This code fails to compile. Which part is wrong?

function area(width: number, height: number): number {
  return width * height;
}

const a = area(3, 4);
const b = area(3);
console.log(a, b);

Question 4 · True or false

A function declared with return type 'never' can finish by returning undefined, as long as it has no return statement.

Question 5 · Multiple choice

Which type correctly describes a variable that holds a function taking a string and returning its length as a number?