Instead of commonly used ambiguous if statements at the start of functions that imply early exit/guards, a guard statement (a la Swift) in TypeScript would be super useful because it allows to:
- Check conditions early and exit if they fail, keeping your main code path clean and positive
- Automatically narrow types after the check, so TypeScript knows a variable is safe to use
- Write "happy path" code that flows forward without deep nesting or defensive checks
It's about writing code that follows the natural flow of what should happen, rather than constantly checking what might go wrong.
example:
// Before: Nested conditions obscure your intent
function processUser(user?: User) {
if (user && user.isActive && user.permissions.includes('admin')) {
// Finally, your actual logic here
doSomethingImportant(user);
}
}
// After: Guards make your main path clear
function processUser(user?: User) {
guard (user) else return;
guard (user.isActive) else return;
guard (user.permissions.includes('admin')) else return;
// Main logic stands out - not buried in conditionals
doSomethingImportant(user);
}