Logo

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 read address.
    • If address is not null/undefined, then read city.
    • If any part is null/undefined, return undefined instead of throwing an error.

2. How to Enable

  1. Install or use TypeScript 3.7 or newer.
  2. In your tsconfig.json, ensure "target" is at least "ES2020" (or "ESNext") and "strictNullChecks" is true if you want full safety:
{ "compilerOptions": { "target": "ES2020", "strictNullChecks": true // ... } }
  1. TypeScript then transpiles optional chaining into JavaScript code compatible with your chosen target.

3. More Features Around ?.

  • Optional Call: someFunction?.(args) calls someFunction(args) only if someFunction 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 or undefined.

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