How optional chaining works in TypeScript ?
Last Updated :
22 Mar, 2022
In this article, we will try to understand how we could perform as well as analyze the working of optional chaining in TypeScript.
TypeScript Optional Chaining:
- TypeScript Optional Chaining is the process of searching and calling variables, methods, parameters that might be nil in existence.
- This particular feature allows the developers to stop encountering the errors which generally come up if things are not defined, and also they could easily handle the undefined things with this particular feature.
How does Optional Chaining work?
- Optional Chaining actually works in a bit of a tricky manner, wherein it first checks the availability of a particular variable or a function.
- If that variable or function is available in the file, then it proceeds with checking the further mentioned variable or function.
- If that variable is not available, it immediately stops checking further and returns "undefined" which a user could easily handle with certain logic.
Let us first analyze how we could make our parameter (when we work in function) or a variable as an optional variable in TypeScript.
Syntax of declaring an optional parameter: Following syntax, we may use in order to make variables as optional in TypeScript ("?" this operator is used for making any variable as optional in TypeScript)-
parameter_name? : return_type
Example 1: In this example, we will be implementing the above-illustrated syntax with an example.
JavaScript
let displayName = (firstName: string , lastName? : string) => {
return "Name : " + firstName + " " + lastName;
}
console.log(displayName("Hello", "World"));
console.log(displayName("GeeksforGeeks"));
Output: Above illustrated code will generate output for both, but in the case of a single parameter so passed it would generate an error, it will just display "undefined".
Name : Hello World
Name : GeeksforGeeks undefined
Now that we have understood how we may declare an optional parameter in TypeScript. Let us now see how we may perform optional chaining in TypeScript using the following examples-
Example 2: In this example, we would be implementing optional chaining while displaying the result or the output.
JavaScript
type User = {
id: number;
name?: {
firstName: string;
lastName?: string;
}
};
const users: User[] = [{
id: 1,
name: {
firstName: "GeeksforGeeks"
}
},
{
id: 2,
name: {
firstName: "Hello",
lastName: "World"
}
},
{
id: 3
},
];
users.map(element => console.log(element.name?.lastName));
Output:
undefined
World
undefined
Example 3: In this example, we will show Optional Chaining in different styles or techniques.
JavaScript
type personDetails = {
name : string,
details? : {
age?: number,
location?: string,
}
}
let person_one: personDetails = {
name: "GeeksforGeeks",
details : {
age: 20,
location: "Noida"
}
}
let person_two: personDetails = {
name: "GeeksforGeeks",
details : {
location: "Noida"
}
}
let person_three: personDetails = {
name: "GeeksforGeeks",
details : {
age: 20,
}
}
let data_1 = person_one.name + " "
+ person_one.details?.age + " "
+ person_one.details?.location;
console.log(data_1);
let data_2 = person_two.name + " "
+ person_two.details?.age + " "
+ person_two.details?.location;
console.log(data_2);
let data_3 = person_three.name + " "
+ person_three.details?.age + " "
+ person_three.details?.location;
console.log(data_3);
Output:
GeeksforGeeks 20 Noida
GeeksforGeeks undefined Noida
GeeksforGeeks 20 undefined
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read