Lesson 7 of 20

Functions & Types

Function Type Expressions

You can define function types to describe the shape of functions — their parameters and return type.

Example
// Function type expression
type MathFn = (a: number, b: number) => number;

const add: MathFn = (a, b) => a + b;
const subtract: MathFn = (a, b) => a - b;

// Callback type
function processData(data: string[], callback: (item: string) => void) {
  data.forEach(callback);
}

processData(["a", "b"], (item) => console.log(item));

Optional & Default Parameters

TypeScript supports optional parameters (with ?) and default values, just like JavaScript but with type safety.

Example
// Optional parameter
function greet(name: string, greeting?: string): string {
  return `${greeting || "Hello"}, ${name}!`;
}

greet("Alice");           // "Hello, Alice!"
greet("Alice", "Hi");     // "Hi, Alice!"

// Default parameter
function createUser(name: string, role: string = "user") {
  return { name, role };
}

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

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

Function Overloads

Function overloads allow you to define multiple signatures for a single function, handling different input types.

Example
// Function overloads
function format(value: string): string;
function format(value: number): string;
function format(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

format("hello");  // "HELLO"
format(3.14159);  // "3.14"