Question
Optional Chaining in TypeScript: Does TypeScript Support `?.` and What Is It Called?
Question
In TypeScript, is the ?. operator supported for safe property access?
For example:
const thing = foo?.bar;
Is this equivalent to something like:
const thing = foo ? foo.bar : null;
Also, what is the standard or most commonly used name for this operator? It can be difficult to search for because the symbol is so short.
Short Answer
By the end of this page, you will understand that TypeScript does support ?., the operator is commonly called optional chaining, and it is used to safely access properties, call methods, or read array elements when a value might be null or undefined. You will also see how it differs from a normal ternary check and how developers use it in real TypeScript code.
Concept
TypeScript supports the ?. operator, and its common name is optional chaining.
Optional chaining lets you safely continue an expression only if the value on the left is not null or undefined. If the value is null or undefined, the whole expression stops and returns undefined instead of throwing an error.
For example:
const city = user?.address?.city;
This means:
- If
userexists, try to readaddress - If
addressexists, try to readcity - If either
useroraddressisnullorundefined, returnundefined
This matters because real programs often deal with missing data:
Mental Model
Think of optional chaining like walking through a building with automatic doors.
- If the next door exists and opens, you keep going
- If you reach a missing or locked door (
nullorundefined), you stop safely - Instead of crashing into the wall with an error, you simply end up with
undefined
Example:
const result = company?.department?.manager?.name;
You are trying to walk through:
companydepartmentmanagername
If any step in that path is missing, the process stops there safely.
Without optional chaining, you would have to manually check every door before opening the next one.
Syntax and Examples
Basic syntax
object?.property
object?.[index]
object?.method()
Optional chaining can be used in three common ways:
1. Safe property access
type User = {
name: string;
profile?: {
bio?: string;
};
};
const user: User = {
name: "Ava"
};
const bio = user.profile?.bio;
console.log(bio); // undefined
Here, profile is optional. If it does not exist, user.profile?.bio safely returns undefined.
2. Safe array access
const items = ["a", "b", "c"];
first = items?.[];
.(first);
Step by Step Execution
Consider this example:
type ApiResponse = {
user?: {
contact?: {
email?: string;
};
};
};
const response: ApiResponse = {
user: {
contact: {
email: "ava@example.com"
}
}
};
const email = response.user?.contact?.email;
console.log(email);
Step by step:
-
response.useris checked- It exists, so evaluation continues
-
response.user.contactis checked- It exists, so evaluation continues
-
response.user.contact.emailis read- It exists and equals
"ava@example.com"
- It exists and equals
-
emailgets the value"ava@example.com"
Real World Use Cases
Optional chaining appears often in real applications where data may be incomplete.
API responses
const avatarUrl = response.data?.user?.profile?.avatarUrl;
APIs often return partial or optional fields.
Form validation
const errorMessage = errors.email?.message;
Validation libraries often store errors only for fields that failed.
Optional callbacks
props.onSave?.();
A component may receive a callback prop, but it may not always be provided.
Configuration objects
const timeout = config.network?.timeout;
Different environments may define different config sections.
Browser or platform features
const language = navigator.languages?.[0];
Some platform APIs may not exist in every runtime.
Real Codebase Usage
In real TypeScript projects, optional chaining is commonly used with a few important patterns.
Reading nested data safely
Developers often consume JSON from APIs where many fields are optional.
const zipCode = order.customer?.address?.zipCode;
Optional function execution
This is a common pattern for event handlers, hooks, and callbacks.
options.onComplete?.(result);
Pairing with nullish coalescing
Optional chaining is often combined with ?? to provide a default value.
const theme = settings.userPreferences?.theme ?? "light";
This means:
- Try to read
theme - If the result is
nullorundefined, use"light"
Guarding without deep nesting
Instead of many if statements:
Common Mistakes
1. Treating ?. as a general falsy check
Broken assumption:
const result = value?.name;
Some beginners think this stops when value is 0, false, or "". It does not. It only stops for:
nullundefined
2. Assuming it returns null
const name = user?.profile?.name;
If the chain stops, the result is undefined, not null.
If you need a fallback:
const name = user?.profile?.name ?? "Anonymous";
3. Using it where the left side cannot be nullish
Comparisons
| Concept | What it checks | Result when missing | Notes |
|---|---|---|---|
foo?.bar | foo is null or undefined | undefined | Precise nullish-safe access |
foo ? foo.bar : null | foo is truthy | null | Treats 0, false, "" as missing |
foo && foo.bar | foo is truthy |
Cheat Sheet
// Property access
obj?.prop
// Array or index access
obj?.[index]
// Method call
obj?.method()
Key rules
?.is called optional chaining- It stops only for
nullorundefined - If it stops, the result is
undefined - It can be used for properties, indexes, and method calls
- It does not treat
0,false, or""as missing
Good examples
const city = user?.address?.city;
const firstItem = list?.[0];
callback?.("done");
Common pairing
const city = user?.address?.city ?? "Unknown";
Rough equivalent
FAQ
What is the ?. operator called in TypeScript?
It is called optional chaining.
Does TypeScript support optional chaining?
Yes. TypeScript supports optional chaining and uses the same ?. syntax as modern JavaScript.
Is foo?.bar the same as foo ? foo.bar : null?
No. Optional chaining checks only for null and undefined, and it returns undefined if access stops.
What does optional chaining return if something is missing?
It returns undefined.
Can I use optional chaining with methods?
Yes.
logger?.log?.("Hello");
Can I use optional chaining with arrays?
Yes.
const first = items?.[0];
Should I always use optional chaining?
No. Use it when a value may legitimately be missing. If a value is required, validate it explicitly.
Mini Project
Description
Build a small TypeScript utility that reads profile information from possibly incomplete user data. This demonstrates how optional chaining helps when working with API-style objects where some nested fields may be missing.
Goal
Create a function that safely reads nested user information and returns sensible fallback values.
Requirements
- Define a TypeScript type for a user with optional nested profile and contact fields.
- Create at least two example users, including one with missing nested data.
- Write a function that returns the user's display name and email safely.
- Use optional chaining to access nested properties.
- Use nullish coalescing to provide default values when data is missing.
Keep learning
Related questions
@Directive vs @Component in Angular: Differences, Use Cases, and When to Use Each
Learn the difference between @Directive and @Component in Angular, including use cases, examples, and when to choose each.
Angular (change) vs (ngModelChange): What’s the Difference?
Learn the difference between Angular (change) and (ngModelChange), when each fires, and which one to use in forms and inputs.
Angular Dependency Injection: Fix "Can't Resolve All Parameters for Component" Errors
Learn why Angular shows "Can't resolve all parameters for component" and how to fix service injection issues in components.