Prompt
Always use null-safe access patterns when dealing with potentially undefined values to prevent runtime errors and improve code robustness. This includes:
- Use optional chaining (
?.) for nested property access:// Instead of assuming objects/properties exist: managedBy: ManagerKind[item.metadata.annotations['grafana.com/managed-by']] // Use optional chaining: managedBy: item.metadata?.annotations?.[AnnoKeyManagerKind] - Use conditional expressions for null-dependent logic:
// Instead of assuming rule exists: const isProvisioned = rulerRuleType.grafana.rule(rule) && Boolean(rule.grafana_alert.provenance); // Use conditional checking: const isProvisioned = rule ? isProvisionedRule(rule) : false; - Return empty collections instead of null/undefined:
// Instead of special values or undefined: return metrics.length === 0 ? MATCH_ALL_LABELS_STR : ...; // Return empty collections: return metrics.length === 0 ? [] : [...]; - Include nullability in type assertions:
// Instead of assuming the type is always present: const parsed = loadAll(raw) as Array<{ kind: string }>; // Account for potential unknown fields and nullability: const parsed = loadAll(raw) as Array<Record<string, unknown> & { kind: string }>;
This approach makes code more defensive and easier to maintain by explicitly handling null cases and preventing “cannot read property of undefined” runtime errors.