Challenge - 5 Problems
Optional Chaining Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of optional chaining with nested objects?
Consider the following TypeScript code using optional chaining. What will be logged to the console?
Typescript
type User = {
name: string;
address?: {
city?: string;
};
};
const user: User = { name: "Alice" };
console.log(user.address?.city ?? "Unknown city");Attempts:
2 left
💡 Hint
Optional chaining returns undefined if the property before it is undefined or null.
✗ Incorrect
Since user.address is undefined, user.address?.city returns undefined, so the nullish coalescing operator (??) returns "Unknown city".
❓ Predict Output
intermediateWhat is the value of variable 'result' after optional chaining?
Given this TypeScript code, what is the value of 'result'?
Typescript
interface Config {
settings?: {
theme?: string;
};
}
const config: Config = { settings: { theme: "dark" } };
const result = config.settings?.theme ?? "light";
Attempts:
2 left
💡 Hint
Check if the optional chaining accesses a defined property.
✗ Incorrect
config.settings is defined and has theme "dark", so optional chaining returns "dark" and nullish coalescing does not apply.
❓ Predict Output
advancedWhat error does this code raise when accessing a possibly undefined method?
Examine this TypeScript code snippet. What error will occur at runtime?
Typescript
type ApiResponse = {
data?: {
getValue?: () => number;
};
};
const response: ApiResponse = {};
const value = response.data?.getValue?.();
console.log(value.toFixed(2));Attempts:
2 left
💡 Hint
Optional chaining returns undefined if the method does not exist, then calling a method on undefined causes an error.
✗ Incorrect
response.data is undefined, so response.data?.getValue?.() returns undefined. Calling toFixed on undefined causes a TypeError.
🧠 Conceptual
advancedHow does optional chaining affect type narrowing in TypeScript?
Which statement best describes how optional chaining influences type narrowing in TypeScript?
Attempts:
2 left
💡 Hint
Think about what happens to the type when you use ?. operator.
✗ Incorrect
Optional chaining returns the property value or undefined if the property is missing, so the type always includes undefined.
❓ Predict Output
expertWhat is the output of this complex optional chaining with arrays and functions?
Analyze the following TypeScript code and determine what is printed to the console.
Typescript
type User = {
getFriends?: () => Array<{ name: string; age?: number }>;
};
const user: User = {
getFriends: () => [
{ name: "Bob", age: 25 },
{ name: "Carol" },
],
};
const friendAge = user.getFriends?.()[1]?.age ?? "Age unknown";
console.log(friendAge);Attempts:
2 left
💡 Hint
Check if the second friend has an age property defined.
✗ Incorrect
The second friend object does not have an age property, so optional chaining returns undefined, triggering the fallback string.
