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.
Optional chaining with types in 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.
undefined instead of error.const user = { name: "Alice" }; console.log(user.address?.street); // undefined
const user = { getAge: () => 30 }; console.log(user.getAge?.()); // 30
undefined safely.const user = {}; console.log(user.getAge?.()); // undefined
const users = [{ name: "Bob" }, null]; console.log(users[1]?.name); // undefined
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.
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);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.
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.
Practice
?. do in TypeScript?Solution
Step 1: Understand optional chaining purpose
Optional chaining?.allows safe access to nested properties or methods without causing runtime errors if the object is null or undefined.Step 2: Identify behavior on null or undefined
If the value before?.is null or undefined, it returns undefined instead of throwing an error.Final Answer:
It safely accesses a property or method, returning undefined if the value is null or undefined. -> Option DQuick Check:
Optional chaining = safe access without error [OK]
- Thinking it throws an error on missing property
- Confusing it with non-null assertion operator
- Assuming it converts values to boolean
name of an object user using optional chaining?Solution
Step 1: Review optional chaining syntax for properties
The correct syntax to access a property safely isobject?.property.Step 2: Check each option
user?.name usesuser?.namewhich is correct. user?.[name] uses brackets incorrectly. user?.name() treatsnameas a method call. user?.name? has invalid syntax.Final Answer:
user?.name -> Option BQuick Check:
Property access with ?. = user?.name [OK]
- Adding parentheses when accessing properties
- Using brackets incorrectly with optional chaining
- Placing ? after property name
type User = { profile?: { age?: number } };
const user: User = {};
const age = user.profile?.age ?? 30;
console.log(age);What will be the output?
Solution
Step 1: Analyze optional chaining and nullish coalescing
The expressionuser.profile?.agesafely tries to accessage. Sinceprofileis undefined, this returns undefined.Step 2: Apply nullish coalescing operator
The??operator returns the right side value30because the left side is undefined.Final Answer:
30 -> Option AQuick Check:
undefined ?? 30 = 30 [OK]
- Expecting undefined instead of default value
- Confusing ?? with || operator
- Assuming runtime error on missing property
interface Data {
info?: {
value: number;
};
}
const data: Data = {};
const val = data?.info.value;Solution
Step 1: Check optional chaining usage
The code usesdata?.info.value. Optional chaining is applied only ondata, butinfocan be undefined.Step 2: Identify missing optional chaining
Accessinginfo.valuewithout optional chaining can cause a runtime error ifinfois undefined. It should bedata.info?.valueordata?.info?.value.Final Answer:
Type error: missing optional chaining before 'value' -> Option CQuick Check:
Optional chaining needed before 'value' to avoid error [OK]
- Applying ?. only once for nested properties
- Assuming optional chaining on parent covers all children
- Ignoring possible undefined intermediate objects
type Config = {
settings?: {
theme?: {
color?: string;
};
};
};
const config: Config = {};
Which expression safely accesses the color property and provides a default of 'blue' if missing?
Solution
Step 1: Use optional chaining for all nested optional properties
Sincesettings,theme, andcolorare optional, use?.at each level:config?.settings?.theme?.color.Step 2: Use nullish coalescing for default value
Use?? 'blue'to provide default only if the value is null or undefined, avoiding falsey value issues.Final Answer:
config?.settings?.theme?.color ?? 'blue' -> Option AQuick Check:
Chain ?. and use ?? for default [OK]
- Using || which treats empty string as false
- Missing optional chaining on some nested properties
- Mixing ?. and non-optional access incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
