DevAcademy
LearnTypeScriptFunction Types
BeginnerTypeScript

Function Types

Learn how to type function parameters, return values, optional/default parameters, and function overloads.

Reading Time

16 min

Lesson

Lesson 10 of 30

Typing Parameters and Return Values

Function parameters are typed with a colon after each name, and the return type is typed after the closing parenthesis.

A Typed Function

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

add(2, "3"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'

Optional and Default Parameters

A parameter marked with ? is optional and may be omitted by the caller. A parameter with a default value is automatically optional too, using that value when omitted.

Optional and Default Parameters Example

function greet(name: string, greeting?: string): string {
  return `${greeting ?? "Hello"}, ${name}!`;
}

function multiply(a: number, b: number = 2): number {
  return a * b;
}

greet("Alice");            // "Hello, Alice!"
multiply(5);                // 10, using the default b = 2

Rest Parameters

A rest parameter collects any number of remaining arguments into a typed array.

Rest Parameters Example

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

sum(1, 2, 3, 4); // 10

Arrow Function Types

Arrow functions are typed the same way as regular functions, and their type can also be described as a standalone function type.

Typed Arrow Function

const square = (n: number): number => n * n;

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

const ascending: Comparator = (a, b) => a - b;

Function Overloads

Overloads let a function accept different combinations of parameter types, each with its own precise return type, by declaring multiple call signatures above a single implementation.

Function Overloads Example

function makeDate(timestamp: number): Date;
function makeDate(year: number, month: number, day: number): Date;
function makeDate(yearOrTimestamp: number, month?: number, day?: number): Date {
  if (month !== undefined && day !== undefined) {
    return new Date(yearOrTimestamp, month, day);
  }
  return new Date(yearOrTimestamp);
}

makeDate(2026, 0, 15); // matches the second overload
makeDate(1700000000);  // matches the first overload

Best Practice

Always type function parameters explicitly, since TypeScript can’t infer them from a caller. Return types can usually be left to inference unless the function is part of a public API, where an explicit return type documents intent clearly.

Interview Questions

Quick Quiz

1. What happens if a parameter has a default value?

2. What does a rest parameter (...args: number[]) collect?

3. What are function overloads used for?