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.

GroupFunctions & Classes
KindSyntax
Strict modeNot 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?: stringOptional 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.
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).
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏