Always handle potentially null or undefined values explicitly using type guards, null coalescing operators, and proper fallback values. This ensures type safety and prevents runtime errors from null references.
Always handle potentially null or undefined values explicitly using type guards, null coalescing operators, and proper fallback values. This ensures type safety and prevents runtime errors from null references.
Key practices:
// Good
const reservedTokens = maxTokens ?? DEFAULT_TOKENS
// Bad - will override 0 with default
const reservedTokens = maxTokens || DEFAULT_TOKENS
// Good
if (typeof data === "object" && data !== null && "property" in data) {
return data.property
}
// Bad
return data?.property || defaultValue
// Good
const description = mode.description ?? mode.whenToUse ?? mode.roleDefinition ?? ''
// Bad
const description = mode.description || mode.whenToUse || mode.roleDefinition
This approach prevents subtle bugs from implicit type coercion and makes null handling intentions clear in the code.
Enter the URL of a public GitHub repository