Enforce type safety by properly handling null and undefined values through TypeScript types and explicit checks. Avoid using non-null assertions (!) or type assertions (as any), and instead:
Enforce type safety by properly handling null and undefined values through TypeScript types and explicit checks. Avoid using non-null assertions (!) or type assertions (as any), and instead:
// Good function process(value: string | null) { if (!value) return 0; return value.length; }
2. Provide explicit defaults using nullish coalescing:
```typescript
// Bad
const count = data?.count || 0; // '' and 0 are treated as false
const name = user?.name || "Anonymous"; // '' is treated as false
// Good
const count = data?.count ?? 0; // only null/undefined trigger default
const name = user?.name ?? "Anonymous";
// Good interface Response { data: string | null } function isResponse(value: unknown): value is Response { return typeof value === ‘object’ && value !== null && ‘data’ in value; } const result = isResponse(response) ? response.data : null; ```
This approach prevents runtime errors, makes null handling explicit, and leverages TypeScript’s type system for better safety.
Enter the URL of a public GitHub repository