How to Use Optional Parameters in TypeScript Interfaces?

In one live TypeScript training program, someone asked about the optional parameters in TypeScript interfaces. In this tutorial, I will explain how to define and use optional parameters in TypeScript interfaces with examples.

What Are Optional Parameters in TypeScript Interfaces?

Optional parameters in TypeScript interfaces allow you to define properties that may or may not be present in an object. This is particularly useful when dealing with configurations or options objects where not all properties are required. Optional parameters are denoted by a question mark (?) after the property name.

Here are some benefits of using optional parameters in TypeScript.

  1. Flexibility: Optional parameters make your interfaces more adaptable to various use cases.
  2. Readability: They improve code readability by clearly indicating which properties are optional.
  3. Maintainability: Easier to maintain and extend your codebase as requirements change.

Read How to Check if an Object is Type of Interface in TypeScript?

Define Optional Parameters in TypeScript Interface

To define an optional parameter in a TypeScript interface, simply add a question mark after the property name. Here’s a basic example:

interface User {
  firstName: string;
  lastName: string;
  middleName?: string;
}

In this example, middleName is an optional parameter. This means that objects conforming to the User interface can either include or omit the middleName property.

TypeScript Interfaces Optional Parameter Examples: User Profiles

Let me show you a more practical example involving user profiles for a web application. Suppose we are developing a platform for managing user profiles in the USA. We might have an interface like this:

interface UserProfile {
  username: string;
  email: string;
  address?: string;
  phoneNumber?: string;
}

Here, address and phoneNumber are optional. This allows us to create user profiles with varying levels of detail:

const user1: UserProfile = {
  username: "john_doe",
  email: "john.doe@example.com"
};

const user2: UserProfile = {
  username: "jane_smith",
  email: "jane.smith@example.com",
  address: "123 Main St, Springfield, IL",
  phoneNumber: "555-1234"
};

Here is a complete TypeScript program.

interface UserProfile {
  username: string;
  email: string;
  address?: string;
  phoneNumber?: string;
}

const user1: UserProfile = {
  username: "john_doe",
  email: "john.doe@example.com"
};

const user2: UserProfile = {
  username: "jane_smith",
  email: "jane.smith@example.com",
  address: "123 Main St, Springfield, IL",
  phoneNumber: "555-1234"
};

// Print user1 details
console.log("User 1:");
console.log("Username:", user1.username);
console.log("Email:", user1.email);
console.log("Address:", user1.address);
console.log("Phone Number:", user1.phoneNumber);

// Print user2 details
console.log("\nUser 2:");
console.log("Username:", user2.username);
console.log("Email:", user2.email);
console.log("Address:", user2.address);
console.log("Phone Number:", user2.phoneNumber);

The exact output is in the screenshot below after executing the TypeScript code.

Optional Parameters in TypeScript Interfaces

Read Declare and Use TypeScript Interfaces with Nested Arrays of Objects

Using Optional Parameters in Functions

Optional parameters are not limited to interfaces; they can also be used in functions. This can be particularly useful when dealing with configuration objects. Here’s an example:

interface Config {
  apiUrl: string;
  timeout?: number;
  headers?: Record<string, string>;
}

function initializeApp(config: Config) {
  const defaultTimeout = 5000;
  const timeout = config.timeout ?? defaultTimeout;
  console.log(`API URL: ${config.apiUrl}`);
  console.log(`Timeout: ${timeout}`);
  if (config.headers) {
    console.log(`Headers: ${JSON.stringify(config.headers)}`);
  }
}

initializeApp({ apiUrl: "https://api.example.com" });
initializeApp({
  apiUrl: "https://api.example.com",
  timeout: 10000,
  headers: { Authorization: "Bearer token" }
});

In this example, the initializeApp function takes a Config object with optional timeout and headers properties. The function provides a default value for timeout if it is not specified.

Conclusion

In this tutorial, I explained how to use optional parameters in TypeScript interfaces with examples. Do let me know if you still have any questions.

You may also like: