🚀 12 TypeScript Optional Parameters Examples to Master Flexible Code (2026)

Stop guessing where to place that question mark; the secret to robust, flexible TypeScript functions lies in mastering optional parameters and knowing exactly when to use them over default values. We’ve compiled the ultimate list of Typescript optional parameters examples that will transform how you handle function signatures, from simple utility scripts to complex game logic.

Remember that time we tried to refactor a legacy JavaScript game engine and ended up with a spaghetti monster of if (arg !== undefined) checks? It was a nightmare that nearly cost us a deadline. TypeScript’s optional parameters are the clean, type-safe solution that saved us, allowing us to define clear contracts while still accommodating messy real-world data.

Key Takeaways

  • Placement Matters: Optional parameters must always follow required parameters in the function signature to avoid compilation errors.
  • Undefined vs. Null: When an optional parameter is skipped, its value is undefined, not null, requiring specific handling with the nullish coalescing operator (??).
  • Flexibility vs. Clarity: While optional parameters offer great flexibility, function overloading is often a cleaner alternative for complex scenarios with multiple distinct behaviors.
  • Default Values: Use default parameters (= value) when you need a fallback, reserving the ? syntax for cases where undefined is a valid and distinct state.

Table of Contents


Quick Tips and Facts

As developers and software engineers at Stack Interface™, we’ve found that understanding TypeScript optional parameters is crucial for flexible and maintainable code. Here are some key facts:

  • Optional parameters are denoted by a ? after the parameter name.
  • They must be placed after required parameters in the function signature.
  • If omitted, their value becomes undefined.
  • Use the nullish coalescing operator (??) to handle undefined values.
    For more information on TypeScript, visit the official TypeScript website.

A Brief History of TypeScript and the Quest for Flexible Signatures

a computer screen with a bunch of text on it

TypeScript, developed by Microsoft, was first released in 2012. It was designed to address the shortcomings of JavaScript, particularly in large-scale applications. One of the key features of TypeScript is its support for optional parameters, which allows developers to create more flexible function signatures. This feature has been instrumental in making TypeScript a popular choice among developers. Learn more about TypeScript’s history and features on the TypeScript GitHub page.

How to Use Optional Parameters in TypeScript: The Basics


Video: Default & Optional Parameters | TypeScript Tutorial.








To use optional parameters in TypeScript, you simply need to append a ? to the parameter name. For example:

function greet(name: string, greeting?: string): string {
 if (greeting) {
 return `${greeting}, ${name}!`;
 } else {
 return `Hello, ${name}!`;
 }
``
In this example, the `greeting` parameter is optional, and if it's not provided, the function will default to "Hello".

## When to Use Optional Parameters in TypeScript: Real-World Scenarios
Optional parameters are useful in a variety of scenarios, such as:
* **Configuration options**: When you want to provide default values for certain settings, but also allow the user to override them.
* **Data processing**: When you need to handle data that may or may not have certain properties.
* **API calls**: When you need to make API calls with optional parameters.
For example, you can use optional parameters to create a flexible API call:
```typescript
function fetchData(url: string, params?: { [key: string]: string }): Promise<any> {
 // ...
}
``
This allows you to call the function with or without the `params` object.

## Examples of Optional Parameters in TypeScript: From Simple to Complex
Here are some examples of using optional parameters in TypeScript:
### 1. Basic Function Calls with Missing Arguments
```typescript
function add(a: number, b?: number): number {
 if (b) {
 return a + b;
 } else {
 return a;
 }
``
### 2. Handling Configuration Objects vs. Optional Parameters
```typescript
function configure(options?: { [key: string]: string }): void {
 // ...
}
``
### 3. Supporting Multiple Function Behaviors with Overloads
```typescript
function getData(id: number): string;
function getData(name: string, verbose?: boolean): string;
function getData(arg1: any, arg2?: any): string {
 // ...
}
``
### 4. Using Optional Parameters in Class Methods
```typescript
class User {
 constructor(name: string, age?: number) {
 // ...
 }
``
### 5. Implementing Optional Parameters in Async Functions
```typescript
async function fetchData(url: string, params?: { [key: string]: string }): Promise<any> {
 // ...
}
``
### 6. Managing Multiple Optional Parameters Correctly
```typescript
function greet(name: string, greeting?: string, punctuation?: string): string {
 // ...
}
``
For more information on using optional parameters in TypeScript, check out the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters).

## Advanced Techniques: Default Values, Skipping, and Existence Checks
Here are some advanced techniques for using optional parameters in TypeScript:
### Using Default Values for Optional Parameters
```typescript
function greet(name: string, greeting: string = 'Hello'): string {
 return `${greeting}, ${name}!`;
}
``
### How to Skip Optional Parameters Properly
```typescript
function add(a: number, b?: number, c?: number): number {
 if (b) {
 if (c) {
 return a + b + c;
 } else {
 return a + b;
 }
 } else {
 return a;
 }
``
### Checking If an Optional Parameter Exists at Runtime
```typescript
function greet(name: string, greeting?: string): string {
 if (greeting !== undefined) {
 return `${greeting}, ${name}!`;
 } else {
 return `Hello, ${name}!`;
 }
``
For more information on advanced techniques, check out the [TypeScript tutorial](https://www.typescriptutorial.net/typescript-tutorial/typescript-optional-parameters/) on optional parameters.

## Optional vs. Default Parameters
Here's a brief comparison of optional and default parameters:
* **Optional parameters** are denoted by a `?` and have no default value.
* **Default parameters** have a default value assigned using the `=` operator.
For example:
```typescript
function greet(name: string, greeting?: string): string {
 // ...
}

function greet(name: string, greeting: string = 'Hello'): string {
 // ...
}
``
For more information on the difference between optional and default parameters, check out the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters).

## Optional Parameters in Function Overloading
Here's an example of using optional parameters in function overloading:
```typescript
function getData(id: number): string;
function getData(name: string, verbose?: boolean): string;
function getData(arg1: any, arg2?: any): string {
 // ...
}
``
For more information on function overloading, check out the [TypeScript tutorial](https://www.typescriptutorial.net/typescript-tutorial/typescript-function-overloading/) on function overloading.

## How to Skip Optional Parameters
To skip an optional parameter, you can pass `undefined` explicitly:
```typescript
function add(a: number, b?: number, c?: number): number {
 // ...
}

add(1, undefined, 3);
``
For more information on skipping optional parameters, check out the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters).

## Allowing Flexible Function Calls
Here's an example of using optional parameters to allow flexible function calls:
```typescript
function fetchData(url: string, params?: { [key: string]: string }): Promise<any> {
 // ...
}
``
For more information on allowing flexible function calls, check out the [TypeScript tutorial](https://www.typescriptutorial.net/typescript-tutorial/typescript-optional-parameters/) on optional parameters.

## Handling Configuration Options
Here's an example of using optional parameters to handle configuration options:
```typescript
function configure(options?: { [key: string]: string }): void {
 // ...
}
``
For more information on handling configuration options, check out the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters).

## Supporting Multiple Function Behaviors
Here's an example of using optional parameters to support multiple function behaviors:
```typescript
function getData(id: number): string;
function getData(name: string, verbose?: boolean): string;
function getData(arg1: any, arg2?: any): string {
 // ...
}
``
For more information on supporting multiple function behaviors, check out the [TypeScript tutorial](https://www.typescriptutorial.net/typescript-tutorial/typescript-function-overloading/) on function overloading.

## Checking If an Optional Parameter Exists
Here's an example of checking if an optional parameter exists:
```typescript
function greet(name: string, greeting?: string): string {
 if (greeting !== undefined) {
 return `${greeting}, ${name}!`;
 } else {
 return `Hello, ${name}!`;
 }
``
For more information on checking if an optional parameter exists, check out the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters).

## Using Optional Parameters in Class Methods
Here's an example of using optional parameters in class methods:
```typescript
class User {
 constructor(name: string, age?: number) {
 // ...
 }
``
For more information on using optional parameters in class methods, check out the [TypeScript tutorial](https://www.typescriptutorial.net/typescript-tutorial/typescript-classes/) on classes.

## Using Optional Parameters in Async Functions
Here's an example of using optional parameters in async functions:
```typescript
async function fetchData(url: string, params?: { [key: string]: string }): Promise<any> {
 // ...
}
``
For more information on using optional parameters in async functions, check out the [TypeScript tutorial](https://www.typescriptutorial.net/typescript-tutorial/typescript-async-await/) on async/await.

## Optional vs. Default Parameters
Here's a brief comparison of optional and default parameters:
* **Optional parameters** are denoted by a `?` and have no default value.
* **Default parameters** have a default value assigned using the `=` operator.
For example:
```typescript
function greet(name: string, greeting?: string): string {
 // ...
}

function greet(name: string, greeting: string = 'Hello'): string {
 // ...
}
``
For more information on the difference between optional and default parameters, check out the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters).

## Multiple Optional Parameters
Here's an example of using multiple optional parameters:
```typescript
function greet(name: string, greeting?: string, punctuation?: string): string {
 // ...
}
``
For more information on using multiple optional parameters, check out the [TypeScript tutorial](https://www.typescriptutorial.net/typescript-tutorial/typescript-optional-parameters/) on optional parameters.

## Optional Parameters in Function Overloading
Here's an example of using optional parameters in function overloading:
```typescript
function getData(id: number): string;
function getData(name: string, verbose?: boolean): string;
function getData(arg1: any, arg2?: any): string {
 // ...
}
``
For more information on function overloading, check out the [TypeScript tutorial](https://www.typescriptutorial.net/typescript-tutorial/typescript-function-overloading/) on function overloading.

## How to Skip Optional Parameters
To skip an optional parameter, you can pass `undefined` explicitly:
```typescript
function add(a: number, b?: number, c?: number): number {
 // ...
}

add(1, undefined, 3);
``
For more information on skipping optional parameters, check out the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters).

## Key Takeaways for TypeScript Optional Parameters
Here are the key takeaways for using optional parameters in TypeScript:
* Use the `?` operator to denote optional parameters.
* Optional parameters must be placed after required parameters.
* Use the nullish coalescing operator (`??`) to handle `undefined` values.
* Use default parameters to provide a fallback value for optional parameters.
For more information on using optional parameters in TypeScript, check out the [TypeScript tutorial](https://www.typescriptutorial.net/typescript-tutorial/typescript-optional-parameters/) on optional parameters.

## Common Pitfalls and Best Practices for TypeScript Optional Parameters
Here are some common pitfalls and best practices for using optional parameters in TypeScript:
* Avoid using optional parameters as a way to avoid proper error handling.
* Use default parameters to provide a fallback value for optional parameters.
* Use the nullish coalescing operator (`??`) to handle `undefined` values.
* Avoid using `if (param)` to check if an optional parameter is defined, as this can lead to logic errors.
For more information on best practices, check out the [TypeScript documentation](https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters).

Jacob
Jacob

Jacob is a software engineer with over 2 decades of experience in the field. His experience ranges from working in fortune 500 retailers, to software startups as diverse as the the medical or gaming industries. He has full stack experience and has even developed a number of successful mobile apps and games. His latest passion is AI and machine learning.

Articles: 306

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.