How to Use TypeScript Optional Function Parameters?

In this tutorial, I will explain how to use optional function parameters in TypeScript. Optional parameters allow you to make some parameters optional when defining functions. Let me explain this with some examples.

What Are Optional Parameters in TypeScript Function?

In TypeScript, optional parameters are parameters that are not required when calling a function. You can define an optional parameter by adding a question mark (?) after the parameter name in the function signature. This feature is particularly useful when you have functions that can be called with varying numbers of arguments.

Why Use Optional Parameters in a Function?

Optional parameters help in several ways:

  • Flexibility: They allow functions to handle a variety of inputs without overloading.
  • Cleaner Code: They reduce the need for multiple function overloads.
  • Default Values: They can be combined with default parameters for more robust function definitions.

How to Define Optional Parameters in TypeScript

To define an optional parameter in a TypeScript function, add a question mark (?) after the parameter name. Here’s the syntax:

function greet(firstName: string, lastName?: string): string {
    if (lastName) {
        return `Hello, ${firstName} ${lastName}!`;
    } else {
        return `Hello, ${firstName}!`;
    }
}

In this example, lastName is an optional parameter. The function can be called with or without it:

console.log(greet("John")); // Output: Hello, John!
console.log(greet("John", "Doe")); // Output: Hello, John Doe!

I executed the above TypeScript code using VS code. You can see the output in the screenshot below:

Optional Parameters in TypeScript

Check out How to Specify Return Type in TypeScript Arrow Functions?

TypeScript Optional Function Parameters Examples

Now, let me show you some examples where you can use optional parameters in TypeScript functions.

Example 1: User Registration

Let us consider a user registration function where some details are optional. Here is the complete TypeScript code.

function registerUser(username: string, email: string, phoneNumber?: string): string {
    if (phoneNumber) {
        return `User ${username} registered with email ${email} and phone number ${phoneNumber}.`;
    } else {
        return `User ${username} registered with email ${email}.`;
    }
}

console.log(registerUser("alice123", "alice@example.com")); 
// Output: User alice123 registered with email alice@example.com.

console.log(registerUser("bob456", "bob@example.com", "555-1234")); 
// Output: User bob456 registered with email bob@example.com and phone number 555-1234.

Here is the exact output in the screenshot below:

How to Use TypeScript Optional Function Parameters

Read How to Return Multiple Values in TypeScript?

Example 2: Booking Appointments

Here is another example where I am going to show you how to use optional parameters in a function in TypeScript.

In a booking system, the time of the appointment might be optional:

function bookAppointment(clientName: string, date: string, time?: string): string {
    if (time) {
        return `Appointment for ${clientName} is scheduled on ${date} at ${time}.`;
    } else {
        return `Appointment for ${clientName} is scheduled on ${date}.`;
    }
}

console.log(bookAppointment("Charlie", "2024-11-10")); 
// Output: Appointment for Charlie is scheduled on 2024-11-10.

console.log(bookAppointment("Dana", "2024-11-10", "10:00 AM")); 
// Output: Appointment for Dana is scheduled on 2024-11-10 at 10:00 AM.

Read How to Use Default Parameter Values in TypeScript?

Example 3: Sending Notifications

Here is another example that explains how to use optional parameters in TypeSctipt functions.

A function to send notifications where the message body might be optional:

function sendNotification(recipient: string, subject: string, messageBody?: string): string {
    if (messageBody) {
        return `Notification sent to ${recipient}: ${subject} - ${messageBody}`;
    } else {
        return `Notification sent to ${recipient}: ${subject}`;
    }
}

console.log(sendNotification("Eve", "Meeting Reminder")); 
// Output: Notification sent to Eve: Meeting Reminder

console.log(sendNotification("Frank", "Meeting Reminder", "Don't forget our meeting at 3 PM.")); 
// Output: Notification sent to Frank: Meeting Reminder - Don't forget our meeting at 3 PM.

Conclusion

Optional parameters in TypeScript are used to define functions that can handle various numbers of arguments. In this tutorial, I have explained how to use optional parameters in TypeScript.

You may also like: