Open In App

How to Create an Interface with Optional Property ?

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript interfaces play a crucial role in defining the structure of objects. One of the powerful features is the ability to specify optional properties within an interface. It allows developers to create flexible structures that can be helpful in various scenarios. In this article, we will explore how to create interfaces with optional properties in TypeScript and understand when and why this feature is useful.

Approach 1: Using the “?” operator

In TypeScript optional property is denoted by adding a “?” to the property name within the interface. This signifies that the property is not mandatory to add when creating objects based on that interface.

Syntax:

property name ?: data type

Example: This example shows the use of ? operator for creating an optional property.

Javascript




interface UserInfo {
    username: string;
    email: string;
    age?: number;
}
 
const user1: UserInfo = {
    username: "sandeep",
    email: "sandeep@example.com",
    age: 25,
};
 
const user2: UserInfo = {
    username: "Jane",
    email: "jane@example.com",
    // No age provided
};
 
console.log(user2)


Output:

{username: 'Jane',email:'jane@example.com'}

Approach 2: Using | operator

Another approach is to explicitly define the properties as either the expected type or undefined within the interface. This indicates that the property can either have a valid value or value is absent.

Syntax:

property name: data type | undefined

Example: This example shows the use of | operator for creating an optional property.

Javascript




interface UserInfo {
    username: string;
    email: string;
    age: number | undefined;
}
 
const user: UserInfo = {
    username: "sandeep",
    email: "sandeep@example.com",
    age: undefined, // Optional property
};
 
console.log(user.age);


Output:

undefined

Approach 3: Utilizing Partial Interface

The Partial type in TypeScript provides another approach to achieving optional properties. It does that by wrapping the interface with Partial type and all properties become optional.

Syntax:

const objName: Partial<interfaceName> = { //properties}

Example: This example shows the use of partial interface for creating an optional property.

Javascript




interface UserInfo {
    username: string;
    email: string;
    age: number;
}
 
const optionalUser: Partial<UserInfo> = {
    username: "GFG",
};
 
console.log(optionalUser.username);


Output:

GFG

Conclusion

Creating interfaces with optional properties in TypeScript enhances code flexibility without compromising with the type safety. When you are defining data structures optional properties can significantly improve the expressiveness and adaptability of your TypeScript code.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads