Optional chaining code example
Example 1: optional chain operator
const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah'
}
};
const dogName = adventurer.dog?.name;
console.log(dogName);
Example 2: optional chaining
let myMap = new Map();
myMap.set("foo", {name: "baz", desc: "inga"});
let nameBar = myMap.get("bar")?.name;
Example 3: optional chaining
function tryGetFirstElement<T>(arr?: T[]) {
return arr?.[0];
}
Example 4: Optional chaining
let x = foo?.bar();
if (foo?.bar?.baz) {
Example 5: optional-chaining operator
if (user?.team?.subscription?.invoices) {
}
Example 6: optional chaining
const array = [1,2,3,4,5];
let arrItem = array?.[4];
console.log(arrItem);