0
0
Typescriptprogramming~5 mins

Optional chaining with types in Typescript

Choose your learning style9 modes available
Introduction

Optional chaining helps you safely access properties or call functions on objects that might be null or undefined. It prevents errors when something is missing.

When you want to get a property from an object that might not exist.
When calling a function that might not be defined on an object.
When working with data from APIs where some fields can be missing.
When accessing nested properties where any level might be undefined.
When you want to avoid writing many checks for <code>null</code> or <code>undefined</code>.
Syntax
Typescript
interface User {
  name?: string;
  address?: {
    street?: string;
    city?: string;
  };
  getAge?: () => number;
}

const user: User = {};

// Access property safely
const street = user.address?.street;

// Call function safely
const age = user.getAge?.();

The ?. operator checks if the value before it is null or undefined. If yes, it stops and returns undefined instead of throwing an error.

Optional chaining works with properties, methods, and array elements.

Examples
Accessing a missing nested property returns undefined instead of error.
Typescript
const user = { name: "Alice" };
console.log(user.address?.street); // undefined
Calling a method safely when it exists.
Typescript
const user = { getAge: () => 30 };
console.log(user.getAge?.()); // 30
Calling a missing method returns undefined safely.
Typescript
const user = {};
console.log(user.getAge?.()); // undefined
Optional chaining works with array elements that might be null.
Typescript
const users = [{ name: "Bob" }, null];
console.log(users[1]?.name); // undefined
Sample Program

This program shows how optional chaining safely accesses properties and methods on two users. The first user has all info, the second is missing some.

Typescript
interface User {
  name?: string;
  address?: {
    street?: string;
    city?: string;
  };
  getAge?: () => number;
}

const user1: User = {
  name: "John",
  address: { street: "Main St", city: "Townsville" },
  getAge: () => 25
};

const user2: User = {
  name: "Jane"
};

function printUserInfo(user: User) {
  console.log(`Name: ${user.name ?? "Unknown"}`);
  console.log(`Street: ${user.address?.street ?? "No street info"}`);
  console.log(`Age: ${user.getAge?.() ?? "Age not available"}`);
}

console.log("User 1 info:");
printUserInfo(user1);

console.log("\nUser 2 info:");
printUserInfo(user2);
OutputSuccess
Important Notes

Time complexity is the same as normal property access, just a small check added.

Optional chaining returns undefined if the value before ?. is null or undefined.

Common mistake: forgetting that optional chaining returns undefined, so you might need to handle that case.

Use optional chaining when you expect some data might be missing, instead of writing many if checks.

Summary

Optional chaining ?. helps safely access properties or call methods on objects that might be missing.

It prevents runtime errors by returning undefined if something is null or undefined.

Use it to write cleaner and safer code when working with uncertain data.