Deep nesting is hard to read. Replace nested if blocks with guard clauses that return early.
// dirty — 4 levels deep
interface User { isActive: boolean; age: number; hasPremium: boolean; }
function solve(user: User | null | undefined): string {
if (user) {
if (user.isActive) {
if (user.age >= 18) {
if (user.hasPremium) {
return 'full-access';
} else {
return 'basic-access';
}
} else {
return 'age-restricted';
}
} else {
return 'inactive';
}
} else {
return 'no-user';
}
}Refactor using guard clauses so the happy path is at the end with minimal nesting.
Sample tests