Member-only story
TypeScript: Elvis Operator (?.
)
The Elvis operator (?.
), officially known as the optional chaining operator, is a handy feature in TypeScript that simplifies accessing deeply nested properties without causing runtime errors. It helps avoid null or undefined errors when trying to access properties of potentially undefined objects.
Let’s dive into what it is and see a real-world use case! 🚀
What is the Elvis Operator?
The Elvis operator (?.
) is used in TypeScript to safely access object properties without explicitly checking if the object is null
or undefined
. If a property or method doesn’t exist, it simply returns undefined
instead of throwing an error.
Syntax:
object?.property // Safely access a property
object?.method() // Safely call a method
array?.[index] // Safely access an array element
Example Without ?.
(Error-Prone Code)
let user: any = null;
console.log(user.name); // ❌ ERROR: Cannot read properties of null
Example With ?.
(Safe Code)
let user: any = null;
console.log(user?.name); // ✅ Output: undefined (no crash)
🚀 Benefit: Prevents TypeScript from throwing an error when trying to access properties of null
or undefined
.
Common Use Case of the…