This post describes the best approach to making a field optional in TypeScript.
How to Make a Field Optional in TypeScript?
To make a field optional in TypeScript use the TypeScript “Optional” property. It is implemented by specifying the “?(question mark)” symbol at the end of the field that the user wants to make optional. Let’s see its practical implementation.
Example 1: Make “type” Field Optional
This example uses the “Optional” property to make a field optional inside the “type”:
name: string,
age?: number,
contact_no: number
};
const user: User = {
name: 'Haroon',
contact_no: 123
};
console.log(user);
In the above code block:
- The “type” keyword creates a type “User” having field names: age, and contact_no. In this type, the “age” field is defined as optional by adding the “?” symbol at its end.
- Next, the “user” object is created of type “User” to initialize its fields. In this object, the “age” field is not initialized.
- Now, the “console.log()” method is applied to display the “user” object.
Output
node main.js //Run .js File
The above-specified code doesn’t generate any error on skipping the optional property.
Example 2: Make the “interface” Field Optional
This example applies the “Optional” property to make the field optional inside an interface:
name: string,
age: number,
contact_no?: number
};
const user: User = {
name: 'Haroon',
age: 35
};
console.log(user);
In the above code block:
- An interface “User” is created having multiple fields in which the two fields “age”, and “contact_no” are defined as “optional”.
- Next, the object of the “User” interface is created for the initialization of its fields.
- Lastly, the “console.log()” method is utilized to display the “user” object.
Output
The terminal successfully shows the initialized field value of the “User” Interface without generating an error on the optional properties.
Note: Apart from “type” and interface, the user can also make the field optional inside the “class”.
Conclusion
In TypeScript, the user can make a field optional by using the “Optional” property symbol “?(question mark)” after them. The field may be inside the “type”, “interface”, or the “class”. Once the field is defined as “optional” then the compiler does not generate any error if it is not specified in the object. The user can make single or multiple fields optional at the same time. This post has described the best approach to making a field optional in TypeScript.