Bird
Raised Fist0
Typescriptprogramming~10 mins

Optional chaining with types in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Optional chaining with types
Start with object
↓
Check if property exists?
No→Return undefined
Yes↓
Access property value
↓
If next property, repeat check
↓
Return final value or undefined
Optional chaining checks each property step-by-step. If any property is missing, it returns undefined instead of error.
Execution Sample
Typescript
const user = { name: "Alice", address: { city: "Wonderland" } };
const city = user?.address?.city;
const zip = user?.address?.zip?.code;
This code safely accesses nested properties using optional chaining, avoiding errors if properties are missing.
Execution Table
StepExpressionCheckResultValue
1user?.addressuser exists?Yes{"city":"Wonderland"}
2user?.address?.cityaddress exists?Yes"Wonderland"
3user?.address?.zipaddress.zip exists?Noundefined
4user?.address?.zip?.codezip exists?Noundefined
💡 Optional chaining stops and returns undefined when a property does not exist.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
user{"name":"Alice","address":{"city":"Wonderland"}}{"name":"Alice","address":{"city":"Wonderland"}}{"name":"Alice","address":{"city":"Wonderland"}}{"name":"Alice","address":{"city":"Wonderland"}}{"name":"Alice","address":{"city":"Wonderland"}}
cityundefinedundefined"Wonderland""Wonderland""Wonderland"
zipundefinedundefinedundefinedundefinedundefined
Key Moments - 2 Insights
Why does accessing user?.address?.zip?.code not cause an error even though zip is missing?
Because optional chaining checks each property step-by-step and returns undefined immediately when a property is missing, preventing runtime errors. See execution_table rows 3 and 4.
What value does city get if user.address.city exists?
It gets the actual value "Wonderland" because all properties exist. See execution_table row 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of user?.address?.city at step 2?
Anull
Bundefined
C"Wonderland"
DError
💡 Hint
Check the 'Value' column at step 2 in the execution_table.
At which step does optional chaining return undefined because a property is missing?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look for the first 'No' in the 'Check' column in execution_table.
If user.address.zip was defined as { code: 12345 }, what would user?.address?.zip?.code be at step 4?
Aundefined
B12345
Cnull
DError
💡 Hint
Think about how optional chaining accesses nested properties when they exist.
Concept Snapshot
Optional chaining syntax: obj?.prop?.subprop
Checks each property safely.
Returns undefined if any property is missing.
Prevents runtime errors from accessing undefined.
Works well with nested objects and optional properties.
Full Transcript
Optional chaining in TypeScript lets you safely access nested properties without errors. It checks each property step-by-step. If a property is missing, it returns undefined immediately instead of throwing an error. For example, user?.address?.city returns the city if address exists, or undefined if not. This helps avoid crashes when some data might be missing. The execution table shows how each step checks for property existence and returns values or undefined accordingly.

Practice

(1/5)
1. What does the optional chaining operator ?. do in TypeScript?
easy
A. It forces a property to be non-nullable.
B. It throws an error if the property does not exist.
C. It converts a value to a boolean.
D. It safely accesses a property or method, returning undefined if the value is null or undefined.

Solution

  1. 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.
  2. Step 2: Identify behavior on null or undefined

    If the value before ?. is null or undefined, it returns undefined instead of throwing an error.
  3. Final Answer:

    It safely accesses a property or method, returning undefined if the value is null or undefined. -> Option D
  4. Quick Check:

    Optional chaining = safe access without error [OK]
Hint: Optional chaining returns undefined if value is null or undefined [OK]
Common Mistakes:
  • Thinking it throws an error on missing property
  • Confusing it with non-null assertion operator
  • Assuming it converts values to boolean
2. Which of the following is the correct syntax to safely access the property name of an object user using optional chaining?
easy
A. user?.name()
B. user?.name
C. user?.[name]
D. user?.name?

Solution

  1. Step 1: Review optional chaining syntax for properties

    The correct syntax to access a property safely is object?.property.
  2. Step 2: Check each option

    user?.name uses user?.name which is correct. user?.[name] uses brackets incorrectly. user?.name() treats name as a method call. user?.name? has invalid syntax.
  3. Final Answer:

    user?.name -> Option B
  4. Quick Check:

    Property access with ?. = user?.name [OK]
Hint: Use ?. before property name without parentheses for safe access [OK]
Common Mistakes:
  • Adding parentheses when accessing properties
  • Using brackets incorrectly with optional chaining
  • Placing ? after property name
3. Consider the following TypeScript code:
type User = { profile?: { age?: number } };
const user: User = {};
const age = user.profile?.age ?? 30;
console.log(age);

What will be the output?
medium
A. 30
B. null
C. Error at runtime
D. undefined

Solution

  1. Step 1: Analyze optional chaining and nullish coalescing

    The expression user.profile?.age safely tries to access age. Since profile is undefined, this returns undefined.
  2. Step 2: Apply nullish coalescing operator

    The ?? operator returns the right side value 30 because the left side is undefined.
  3. Final Answer:

    30 -> Option A
  4. Quick Check:

    undefined ?? 30 = 30 [OK]
Hint: ?. returns undefined if missing; ?? provides default value [OK]
Common Mistakes:
  • Expecting undefined instead of default value
  • Confusing ?? with || operator
  • Assuming runtime error on missing property
4. Identify the error in this TypeScript code snippet:
interface Data {
  info?: {
    value: number;
  };
}

const data: Data = {};
const val = data?.info.value;
medium
A. No error, code works fine
B. Runtime error: accessing property of undefined
C. Type error: missing optional chaining before 'value'
D. Syntax error: optional chaining used incorrectly on data

Solution

  1. Step 1: Check optional chaining usage

    The code uses data?.info.value. Optional chaining is applied only on data, but info can be undefined.
  2. Step 2: Identify missing optional chaining

    Accessing info.value without optional chaining can cause a runtime error if info is undefined. It should be data.info?.value or data?.info?.value.
  3. Final Answer:

    Type error: missing optional chaining before 'value' -> Option C
  4. Quick Check:

    Optional chaining needed before 'value' to avoid error [OK]
Hint: Chain ?. for each possibly undefined property [OK]
Common Mistakes:
  • Applying ?. only once for nested properties
  • Assuming optional chaining on parent covers all children
  • Ignoring possible undefined intermediate objects
5. Given this nested object type and variable:
type Config = {
  settings?: {
    theme?: {
      color?: string;
    };
  };
};

const config: Config = {};

Which expression safely accesses the color property and provides a default of 'blue' if missing?
hard
A. config?.settings?.theme?.color ?? 'blue'
B. config.settings.theme.color || 'blue'
C. config.settings?.theme.color ?? 'blue'
D. config?.settings.theme?.color || 'blue'

Solution

  1. Step 1: Use optional chaining for all nested optional properties

    Since settings, theme, and color are optional, use ?. at each level: config?.settings?.theme?.color.
  2. 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.
  3. Final Answer:

    config?.settings?.theme?.color ?? 'blue' -> Option A
  4. Quick Check:

    Chain ?. and use ?? for default [OK]
Hint: Chain ?. for each optional and use ?? for default [OK]
Common Mistakes:
  • Using || which treats empty string as false
  • Missing optional chaining on some nested properties
  • Mixing ?. and non-optional access incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard