Does Typescript support the ?. operator?
Yes, TypeScript supports the optional chaining operator (?.
) starting from TypeScript 3.7. It allows you to safely access nested properties without causing runtime errors if an intermediate value is null
or undefined
.
1. Example Usage
interface User { name: string; address?: { city?: string; }; } const user: User = { name: "Alice", }; // Without optional chaining, accessing user.address.city could throw console.log(user?.address?.city); // undefined, no error
user?.address?.city
means:- If
user
is not null/undefined, then readaddress
. - If
address
is not null/undefined, then readcity
. - If any part is
null
/undefined
, returnundefined
instead of throwing an error.
- If
2. How to Enable
- Install or use TypeScript 3.7 or newer.
- In your tsconfig.json, ensure
"target"
is at least"ES2020"
(or"ESNext"
) and"strictNullChecks"
istrue
if you want full safety:
{ "compilerOptions": { "target": "ES2020", "strictNullChecks": true // ... } }
- TypeScript then transpiles optional chaining into JavaScript code compatible with your chosen
target
.
3. More Features Around ?.
- Optional Call:
someFunction?.(args)
callssomeFunction(args)
only ifsomeFunction
is not null/undefined. - Non-Null Assertion + Optional: If you’re certain something exists, you can do
obj!.prop
, but typically optional chaining is safer if you’re not sure.
4. Why Use Optional Chaining?
- Avoids “Cannot read property X of undefined” errors at runtime.
- Shorter and more readable than multiple
if
checks. - Works well with union types that might include
null
orundefined
.
If you'd like to strengthen your JavaScript (and TypeScript) foundations, check out the Grokking JavaScript Fundamentals course by DesignGurus.io. This course delves into crucial JS topics like closures, prototypes, and async patterns—helping you use TypeScript’s advanced features, including optional chaining, more effectively.
CONTRIBUTOR
TechGrind