Parameters and overloads
Overview
Real functions are rarely just “two required arguments”. Some arguments are optional, some have defaults, some functions take any number of values, and some behave differently depending on what you pass. This lesson covers how to type all of these — and when to reach for overloads.
Optional parameters
Add ? after the name:
function greet(name: string, greeting?: string): string {
return `${greeting ?? "Hello"}, ${name}!`;
}
greet("Asha"); // "Hello, Asha!"
greet("Asha", "Welcome"); // "Welcome, Asha!"Inside the function, greeting has type string | undefined, so you must handle the missing case. Optional parameters must come after required ones.
Default values
A default is usually nicer than ? + ??:
function greet(name: string, greeting = "Hello"): string {
return `${greeting}, ${name}!`;
}The parameter is optional for callers, and inside the function it’s simply a string — never undefined. The type is inferred from the default; add an annotation when the default is narrower than what you accept:
function resize(width: number, unit: "px" | "rem" = "px") { … }Rest parameters
...name collects any number of remaining arguments into an array, so its type is an array type:
function sum(...values: number[]): number {
return values.reduce((total, v) => total + v, 0);
}
sum(); // 0
sum(1, 2, 3); // 6
sum(1, "2");
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.Spreading an array into a call works too: sum(...prices).
Options objects
Once a function has more than two or three optional settings, positional arguments become unreadable — what does createUser("Asha", undefined, true, false) mean? Take an options object instead:
type UserOptions = {
role?: "admin" | "viewer";
active?: boolean;
sendWelcome?: boolean;
};
function createUser(name: string, options: UserOptions = {}) {
const { role = "viewer", active = true, sendWelcome = false } = options;
return { name, role, active, sendWelcome };
}
createUser("Asha", { sendWelcome: true });Or destructure directly in the parameter list — the type annotation goes after the whole pattern:
function createUser(name: string, { role = "viewer", active = true }: UserOptions = {}) { … }Callers get autocomplete for every option, can pass them in any order, and the excess property check catches misspelled option names.
Overloads
Sometimes a function’s return type depends on its argument type. Suppose parse turns one string into one number, and an array of strings into an array of numbers. A union signature loses information:
function parse(input: string | string[]): number | number[] { … }
const n = parse("42"); // number | number[] — but we know it's a number!Overloads let you list each way the function can be called:
function parse(text: string): number;
function parse(texts: string[]): number[];
function parse(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
parse("42"); // number
parse(["1", "2"]); // number[]How it works:
- The first lines, without bodies, are the overload signatures. Callers see only these — the editor even shows “+1 overload”.
- The last one is the implementation signature. It must be compatible with every overload, and it’s not callable directly.
- TypeScript picks the first overload that matches the arguments. Order them from most specific to least specific.
If nothing matches, the error lists what was tried:
parse(42);
// error TS2769: No overload matches this call.Overloads are a last resort
Overloads are verbose, and TypeScript only checks that the implementation is compatible with them, not that it does the right thing for each one. Before writing them, try:
- optional parameters or a union — if the return type doesn’t depend on the arguments;
- generics (Generic functions) — if the output type follows the input type, as in
first<T>(items: T[]): T | undefined.
Overloads shine in exactly one situation: a small, fixed set of input types that map to different output types. You’ll see them all over the DOM types — document.createElement("canvas") returns an HTMLCanvasElement, createElement("img") an HTMLImageElement — which is why they’re worth knowing.
Guidelines: required first, then optional or defaulted; options objects beyond two or three settings; rest parameters for “any number of”; overloads only when the return type depends on the argument.
Flexible functions
Write four functions. (1) average(...values: number[]): number — returns 0 when called with no values. (2) createUser(name: string, options?: { role?: "admin" | "viewer"; active?: boolean }) — returns an object with name, role (default "viewer") and active (default true), using destructuring with defaults. (3) formatDate(date: Date, style: "short" | "long" = "short") — "short" gives 2026-12-04, "long" gives 4 December 2026 (use toLocaleDateString("en-GB", …) with timeZone: "UTC"). (4) An overloaded toList that returns string[] when given a string (split on commas, trimmed) and number[] when given a number (that many numbers from 1). Call each and print the results; show with // @ts-expect-error that toList(true) is rejected.
// 1. average
// 2. createUser
// 3. formatDate
// 4. toList overloads// 1. average
function average(...values: number[]): number {
if (values.length === 0) return 0;
return values.reduce((sum, v) => sum + v, 0) / values.length;
}
// 2. createUser
type Role = "admin" | "viewer";
function createUser(name: string, { role = "viewer", active = true }: { role?: Role; active?: boolean } = {}) {
return { name, role, active };
}
// 3. formatDate
function formatDate(date: Date, style: "short" | "long" = "short"): string {
if (style === "short") return date.toISOString().slice(0, 10);
return date.toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" });
}
// 4. toList overloads
function toList(input: string): string[];
function toList(input: number): number[];
function toList(input: string | number): string[] | number[] {
if (typeof input === "string") return input.split(",").map((s) => s.trim());
return Array.from({ length: input }, (_, i) => i + 1);
}
console.log(average(4, 8, 15), average()); // 9 0
console.log(createUser("Asha")); // { name: 'Asha', role: 'viewer', active: true }
console.log(createUser("Ravi", { role: "admin" }));
const d = new Date("2026-12-04T00:00:00Z");
console.log(formatDate(d), formatDate(d, "long")); // 2026-12-04 4 December 2026
const words = toList("tea, coffee ,cake"); // string[]
const nums = toList(3); // number[]
console.log(words, nums);
// @ts-expect-error -- no overload accepts a boolean
toList(true);Summary
param?: Tandparam = defaultmake parameters optional; optional ones must come after required ones.- Rest parameters collect extra arguments into a typed array:
...values: number[]. - For many options, take one options object and destructure it with defaults.
- Overloads list several call signatures above one implementation; callers only see the overloads.
- Prefer unions, optional parameters or generics; use overloads when the return type depends on the argument type.