TypeScript: Optional and Default Parameters
In TypeScript, functions are a core building block. Often, you'll want to create functions that can be called with fewer arguments than defined, or provide fallback values for certain parameters. This is where optional and default parameters shine, making your code more flexible and readable.
Optional Parameters
Optional parameters allow you to omit arguments when calling a function. In TypeScript, you mark an optional parameter by appending a question mark (?) after its name. When an optional parameter is not provided, its value will be
undefined
Use '?' to make a parameter optional.
Marking a parameter with '?' means you don't have to provide a value for it when calling the function. If it's not provided, it will be undefined
.
Consider a function that greets a user, optionally including a title. If the title isn't provided, the greeting will be simpler. This is achieved by marking the title
parameter with a question mark: function greet(name: string, title?: string) { ... }
. When calling greet('Alice')
, title
will be undefined
. When calling greet('Bob', 'Dr.')
, title
will be 'Dr.'
.
You append a question mark (?) after the parameter name.
Default Parameters
Default parameters provide a way to assign a default value to a parameter if no argument is passed for it during the function call. This is a more direct way to ensure a parameter always has a value, avoiding the need for explicit
undefined
Assign a default value using '='.
By assigning a value directly to a parameter in the function signature (e.g., param: type = defaultValue
), that value is used if the argument is omitted.
Imagine a function to calculate the volume of a box, where the height defaults to 1 if not specified. You can write this as: function calculateVolume(length: number, width: number, height: number = 1) { ... }
. If you call calculateVolume(10, 5)
, height
will be 1
. If you call calculateVolume(10, 5, 3)
, height
will be 3
.
Feature | Optional Parameter | Default Parameter |
---|---|---|
Syntax | parameterName?: type | parameterName: type = defaultValue |
Value if omitted | undefined | Assigned default value |
Use case | When a parameter might not be provided and undefined is an acceptable state. | When a parameter should always have a specific fallback value if not provided. |
Default parameters are evaluated at runtime. This means you can use expressions or other function calls as default values.
Combining Optional and Default Parameters
You can use both optional and default parameters in the same function. However, it's important to note that optional parameters must come after any parameters with default values in the function signature. This is because if an optional parameter is omitted, TypeScript needs to know which parameter was omitted to correctly assign values.
Consider a function function processData(data: string, options?: { retries?: number, timeout: number })
. Here, options
itself is an optional parameter. Inside options
, retries
is also optional, while timeout
is required if options
is provided. This demonstrates nested optionality.
Text-based content
Library pages focus on text content
Optional parameters must come after parameters with default values.
Practical Applications
Optional and default parameters are incredibly useful for creating flexible APIs. They allow users of your functions to provide only the necessary information, making your code cleaner and easier to use. This is particularly relevant in full-stack development where functions might handle various configurations or optional features.
Learning Resources
The definitive guide to functions in TypeScript, covering parameters, return types, and more.
Detailed explanation of how to use optional parameters in TypeScript functions.
Learn how to set default values for function parameters in TypeScript.
A clear explanation of default parameters, which are also a feature in modern JavaScript and directly applicable to TypeScript.
An in-depth article exploring various aspects of TypeScript functions, including parameter handling.
A video tutorial that visually explains function declaration and parameter usage in TypeScript.
A practical guide with examples on how to implement optional parameters in your TypeScript code.
A community discussion addressing the important rule about the order of default and optional parameters.
A developer's perspective on the benefits and usage of default parameters in TypeScript.
An interactive online editor to experiment with TypeScript code, including optional and default parameters.