What is double question mark in TypeScript?
The double question mark, also known as the optional chaining operator, is a feature introduced in TypeScript 3.7. It is a convenient way to access properties or methods of an object without having to check if the object is null or undefined. This operator helps in avoiding common runtime errors and makes the code more readable and maintainable.
In TypeScript, the double question mark operator is represented by `?.`. When used in an expression, it allows you to safely access nested properties or methods of an object. If any of the properties or methods in the chain are null or undefined, the operator returns undefined instead of throwing a TypeError.
Let’s take a look at some examples to understand how the double question mark operator works in TypeScript.
Consider the following object:
“`typescript
const person = {
name: ‘John’,
address: {
street: ‘123 Main St’,
city: ‘Anytown’
}
};
“`
To access the `city` property of the `address` object, you can use the double question mark operator as follows:
“`typescript
const city = person.address?.city;
“`
In this example, if the `person` object is null or undefined, or if the `address` property is null or undefined, the `city` variable will be assigned the value `undefined`.
Now, let’s consider a more complex scenario where you want to access a nested property:
“`typescript
const user = {
name: ‘Alice’,
profile: {
bio: {
age: 25,
hobbies: [‘reading’, ‘hiking’]
}
}
};
“`
To access the `age` property of the `bio` object within the `profile` object, you can use the double question mark operator as follows:
“`typescript
const age = user.profile?.bio?.age;
“`
In this case, if any of the properties (`user`, `profile`, or `bio`) are null or undefined, the `age` variable will be assigned the value `undefined`.
The optional chaining operator is particularly useful when dealing with optional parameters or properties in functions. It allows you to safely access these parameters or properties without having to check for their existence explicitly.
In conclusion, the double question mark operator in TypeScript is a powerful feature that simplifies the process of accessing properties or methods of an object. By using this operator, you can avoid runtime errors and make your code more concise and readable.