Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk3 min

TypeScript Optional Parameters: A Practical Guide

Add ? to a trailing TypeScript parameter when callers may omit it. Learn what value the function receives, when a default is better, and how callback types express optional arguments.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To make a TypeScript parameter optional, add ? after its name: function greet(name: string, greeting?: string). Callers may omit that trailing argument, and the function receives undefined when they do. Use a default initializer instead when omission should select a fallback value.

How to declare an optional parameter

Parameters are required unless you mark them optional with ?. The optional marker follows the parameter name and its type:

As an Amazon Associate I earn from qualifying purchases.

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

greet("Ada");
greet("Ada", "Welcome");

Because greeting may be undefined, the function must account for that possibility. With strictNullChecks enabled, TypeScript treats an optional parameter as possibly undefined. Optional does not mean nullable: callers cannot pass null unless the declared type explicitly includes it, such as string | null.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What happens when the argument is omitted?

An omitted argument has the runtime value undefined. This matches JavaScript function behavior. When there is no single appropriate fallback, keep the parameter optional and handle the missing value in the function body, as in the greet example above.

Optional parameters versus default parameters

A default initializer gives the parameter a value if the caller omits the argument or explicitly passes undefined:

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

greet("Ada");
greet("Ada", undefined); // uses "Hello"

Unlike a bare optional parameter, a defaulted parameter is initialized before the function body runs. The function’s exposed type allows that argument to be omitted, but does not include the default value itself.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem
Need Signature What the function must handle
Callers may omit a trailing argument, with no universal fallback value?: T The value may be undefined.
Omission or explicit undefined should select a fallback value = fallback The initializer supplies the value before the body runs.

Can an optional parameter come before a required one?

A parameter marked with ? must come after required parameters. If you need a value that callers can leave out before a later required positional argument, consider changing the parameter order or using an options object.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A default-initialized parameter is a different case: it may appear before a required parameter, but its position still matters at the call site. To supply the later argument, the caller must fill the earlier slot, often with undefined:

function configure(mode = "safe", file: string): void {
  // ...
}

configure(undefined, "settings.json");

For APIs where that positional placeholder would be awkward, redesigning the signature or passing named fields in an options object can make calls clearer.

How optionality works in callback types

Optionality in a callback type describes what the code invoking the callback may omit. It does not mean the callback implementation is free to ignore an argument.

If the callback is always called with an index, keep that argument required in its type. Implementations can still accept fewer parameters when they do not need the index:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
type EachCallback<T> = (value: T, index: number) => void;

function each<T>(items: T[], callback: EachCallback<T>): void {
  items.forEach((value, index) => callback(value, index));
}

each(["a", "b"], value => console.log(value));

Only declare the callback argument optional if the invoking function might actually call it without that argument. In that case, callback implementations must handle the value being undefined:

type MaybeIndexedCallback<T> = (value: T, index?: number) => void;

The TypeScript Handbook states: “When writing a function type for a callback, never write an optional parameter unless you intend to call the function without passing that argument”. See More on Functions.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When to use a rest parameter instead

An optional parameter allows a particular argument to be omitted; it does not represent an unlimited number of arguments. For an unbounded sequence, use a rest parameter. The function receives the remaining arguments as an array:

function collect(...values: string[]): string[] {
  return values;
}

collect("one", "two", "three");

For more on parameter syntax and behavior, see the TypeScript Handbook pages on functions and type compatibility.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.