TypeScript Reference ยท Literal and Object Types
TypeScript optional and default parameters
Reference for TypeScript optional parameters (?) and default values: ordering rules, undefined handling, types inferred from defaults, and callback compatibility.
A parameter followed by ? is optional: callers may leave it out, and inside the function its type is the declared type plus undefined. A parameter with a default value (= expr) is also optional for callers, but inside the function it is never undefined, because the default replaces a missing or undefined argument.
Required parameters cannot follow an optional one, except when the later parameter has a default value (and then the caller must pass undefined to skip the earlier one).
function greet(name: string, greeting?: string, punctuation = "!") { return `${greeting ?? "Hello"}, ${name}${punctuation}`; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
function f(a: A, b?: B, c: C = defaultC, d = defaultD): void {} type G = (a: A, b?: B) => void;
| Form | Type inside the function | Caller may omit? |
|---|---|---|
b?: B |
B | undefined |
Yes |
c: C = v |
C |
Yes (or pass undefined) |
d = v |
Type inferred from v (widened) |
Yes |
e: E | undefined |
E | undefined |
No: the argument must be passed explicitly (even as undefined) |
Edge cases: a parameter that is B | undefined but not marked ? must still be provided (you can pass undefined). With exactOptionalPropertyTypes the setting applies to properties, not parameters. A parameter cannot have both ? and an initializer.
Usage notes
- Order: optional parameters must come after required ones; a defaulted parameter may precede required ones, but then it is effectively required positionally.
- Evaluation: default expressions are evaluated at each call, in the parameter scope, left to right, so they can use earlier parameters.
nullis notundefined: onlyundefinedtriggers a default.- Function length:
fn.lengthcounts parameters before the first optional or defaulted one. - Compatibility: a function with required parameters is not assignable to a type where those parameters are optional if it would be called without them under strictness rules; see Function types.
- Options objects: for more than three optional values, take one object parameter with optional properties and a default
= {}. - Overloads are an alternative when different combinations of arguments mean different things.