Optional chaining is a feature in TypeScript that allows you to access properties of an object or call a method, even if the object is ‘undefined‘ or ‘null‘. Instead of throwing an error due to accessing properties of ‘undefined‘ or ‘null‘, it simply returns ‘undefined‘. TypeScript handles optional chaining using the ‘?.‘ operator.
In TypeScript, optional chaining works for properties and methods, as well as function and constructor calls. Here’s a brief explanation of each case:
1. **Optional Property Access** When accessing a property, use the ‘?.‘ operator to perform an optional property access.
const propertyValue = someObject?.property;
If ‘someObject‘ is ‘undefined‘ or ‘null‘, ‘propertyValue‘ will be ‘undefined‘.
2. **Optional Method Access** Similar to properties, you can use the ‘?.‘ operator to call a method too.
const methodResult = someObject?.method();
If ‘someObject‘ is ‘undefined‘ or ‘null‘, or the method does not exist, ‘methodResult‘ will be ‘undefined‘.
3. **Optional Function Call** When dealing with functions, you can use the ‘?.()‘ syntax to make the call optional.
const functionResult = someFunction?.();
If ‘someFunction‘ is ‘undefined‘ or ‘null‘, ‘functionResult‘ will be ‘undefined‘.
4. **Optional Constructor Call** When initializing an object using a constructor, use the ‘?.‘ operator to make the call optional.
const newInstance = SomeClass?.();
If ‘SomeClass‘ is ‘undefined‘ or ‘null‘, ‘newInstance‘ will be ‘undefined‘.
Let’s see an example:
interface User {
name: string;
address?: {
street: string;
city: string;
};
}
const user: User = {
name: "John",
};
const cityName = user?.address?.city; // Since 'address' is missing, 'cityName' will be 'undefined'.
In this example, we have defined a ‘User‘ interface with an optional ‘address‘ property. When trying to access the ‘city‘ property, we use optional chaining to avoid errors if the ‘address‘ is not provided. As a result, ‘cityName‘ is assigned the value ‘undefined‘.
User = {
name: String,
address?: {
street: String,
city: String,
}
}
user = {
name: "John",
}
cityName = user?.address?.city // "undefined"