How to usethe “?” operator in Javascript
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'}
How to Create an Interface with Optional Property ?
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.
Table of Content
- Using the “?” operator
- Using | operator
- Utilizing Partial Interface
Contact Us