thecodex.expert · The Codex Family of Knowledge
TypeScript

Functions in TypeScript

Passing too few or the wrong-shaped arguments to a function is caught before the code ever runs — not discovered when a user hits that code path in production.

TypeScript 6.0 Optional params: name? Last verified:
Canonical Definition

A function's parameters and return value can each carry a type annotation, checked at every call site at compile time. A parameter marked with ? is optional; giving a parameter a default value makes it optional automatically, with TypeScript inferring its type from the default. Function overloads let a single function name accept several distinct signatures, each with its own parameter and return types, useful when a function's behavior genuinely depends on which shape of arguments it receives.

Typed parameters and return values

The return type is usually inferred automatically, but annotating it explicitly documents intent and catches a mistaken return path immediately.

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

add(2, "3");   // COMPILE ERROR: argument of type string not assignable to number

Optional and default parameters

An optional parameter (?) may be undefined inside the function body and must be checked before use; a default value makes a parameter optional at the call site while guaranteeing it's never undefined inside the function.

TypeScriptoptional_default.ts
function greet(name: string, greeting?: string): string {
    return `${greeting ?? "Hello"}, ${name}!`;   // greeting might be undefined
}

function greetWithDefault(name: string, greeting: string = "Hello"): string {
    return `${greeting}, ${name}!`;   // greeting is NEVER undefined here
}

greet("Alice");                    // fine, greeting is undefined
greetWithDefault("Bob");            // fine, greeting defaults to "Hello"

Function overloads: one name, multiple signatures

The overload signatures (no body) describe every valid call pattern; the final implementation signature must be compatible with all of them, and is the only one with an actual function body.

TypeScriptoverloads.ts
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(1746576000000);      // matches the first overload
makeDate(2026, 4, 6);          // matches the second overload
// makeDate(2026, 4);          // COMPILE ERROR: no overload matches this call

Sources

1
Microsoft. TypeScript Handbook, "More on Functions", typescriptlang.org/docs/handbook/2/functions.html.