arg?: T Optional and Default Parameters
Last updated: 2026-10-22
arg?: T Optional and Default Parameters
? marks an optional parameter (may be omitted), = gives one a default (used when omitted). Together they let callers pass only what is necessary — the first tool for friendly signatures.
| Group | Functions & Classes |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
function buildLabel(orderId: number, prefix = "ORD", note?: string): string {
const base = `${prefix}-${String(orderId).padStart(5, "0")}`;
return note ? `${base} (${note})` : base;
}
⚙️ Parameters
| prefix = "ORD" | Default parameter: used when omitted; its type is inferred from the default value |
|---|---|
| note?: string | Optional parameter: undefined when omitted, so its real type is string | undefined and needs narrowing before use |
Returns:Annotate or infer the return type as usual; if an optional parameter participates in the logic, its undefined branch must be handled.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
ORD-00042
VIP-00042
ORD-00042 (rush)
(Runtime output after transpilation; an omitted note is undefined — no "undefined" ever leaks into the label)
💡 Notes
ℹ️ Info Optional parameters must come after required ones; default parameters may sit anywhere, but skipping one in the middle requires passing undefined explicitly.
⚠️ Note note?: string is really string | undefined — calling string methods on it directly errors; narrow with if (note) first or use a default instead.
💡 Tip With more than 3 parameters, switch to an options object (options: { prefix?: string; note?: string }) — more readable and extensible than a long positional list.
🏷️ Related Functions & Classes
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Can default and optional parameters be combined?
A Yes, and it's common: prefix = "ORD" is both omissible and backed by a default. A pure ? parameter is undefined when omitted — the body must handle that.
Q Can a required parameter follow an optional one?
A No — required parameters must come first. Default parameters in the middle are the exception: skip them by passing undefined, e.g. buildLabel(42, undefined, "rush").
Q Default parameters or overloads?
A Use defaults/optional for "fewer arguments"; overloads are for genuinely different parameter types (e.g. string vs Date driving different logic).