When using optional chaining (`?.`), ensure that **all subsequent operations** in the chain are also protected from null/undefined values. A common mistake is only protecting the initial object access while leaving subsequent method calls or property accesses vulnerable.
When using optional chaining (?.
), ensure that all subsequent operations in the chain are also protected from null/undefined values. A common mistake is only protecting the initial object access while leaving subsequent method calls or property accesses vulnerable.
Problems to avoid:
// PROBLEMATIC: scrollSnapList() result is unprotected
api?.scrollSnapList().map(...)
// PROBLEMATIC: OR operator doesn't work with void returns
onClick={() => onClickStep?.(index, setStep) || onClickStepGeneral?.(index, setStep)}
Better approaches:
// BEST: Add length check for extra safety api?.scrollSnapList()?.length > 0 && api.scrollSnapList().map(…)
2. Use proper conditionals for control flow:
```typescript
// Option 1: Explicit conditional
onClick={() => {
if (onClickStep) {
onClickStep(index, setStep);
} else {
onClickStepGeneral?.(index, setStep);
}
}}
// Option 2: Execute both with separate optional chaining
onClick={() => {
onClickStep?.(index, setStep);
onClickStepGeneral?.(index, setStep);
}}
Always trace through the entire chain of operations when working with potentially null/undefined values to ensure each step is properly protected.
Enter the URL of a public GitHub repository