Back to all reviewers

Handle optional values safely

ant-design/ant-design
Based on 4 comments
TypeScript

Always provide safe defaults or fallbacks when working with optional or potentially undefined values. Avoid using non-null assertion operators (`!`) on optional parameters, and ensure proper handling in type checking and value merging scenarios.

Null Handling TypeScript

Reviewer Prompt

Always provide safe defaults or fallbacks when working with optional or potentially undefined values. Avoid using non-null assertion operators (!) on optional parameters, and ensure proper handling in type checking and value merging scenarios.

Key practices:

  • Use default objects instead of non-null assertions: val(info || { props: {} }) instead of val(info!)
  • Order type checks to handle undefined cases first: check for object & not null, then boolean, then provide defaults
  • Provide fallbacks for missing values: color: var(--ant-tooltip-color, ${tooltipColor}) instead of assuming the CSS variable exists
  • Skip undefined values in object merging to preserve existing values rather than overwriting with undefined

Example:

// ❌ Dangerous - assumes info exists
return val(info!) as T;

// ✅ Safe - provides default
return val(info || { props: {} as Props }) as T;

// ❌ No fallback for missing CSS variable  
color: 'var(--ant-tooltip-color)',

// ✅ Provides fallback
color: `var(--ant-tooltip-color, ${tooltipColor})`,

This prevents runtime errors and ensures predictable behavior when dealing with optional or missing values.

4
Comments Analyzed
TypeScript
Primary Language
Null Handling
Category

Source Discussions