Lesson 4 / 7

Functions and Optional Parameters

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

A parameter with a default value (= "Hello") is automatically optional. A parameter marked with ? is optional without a default, meaning it could be undefined inside the function — ?? (the nullish coalescing operator) provides a fallback exactly like in plain JavaScript.

Function types

type MathOperation = (a: number, b: number) => number;nnconst add: MathOperation = (a, b) => a + b;nconst subtract: MathOperation = (a, b) => a - b;

You can name the shape of a function itself — its parameter types and return type — and reuse that shape anywhere a matching function is expected, exactly like an object interface but for callable values.

void vs undefined return types

function logMessage(message: string): void {n    console.log(message);n    // no return statement -- and that's expected heren}

void specifically means “this function’s return value should never be used,” which is subtly different from a function that explicitly returns undefinedvoid communicates intent to both the compiler and to anyone reading the function signature later.

Overloaded function signatures

function makeId(value: number): number;nfunction makeId(value: string): string;nfunction makeId(value: number | string): number | string {n    return value;n}

This lets TypeScript know that calling makeId(5) returns a number specifically, and makeId("abc") returns a string specifically — more precise than the single, broader number | string union the actual implementation uses.