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
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