Guard statement for early exit / positive coding

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:

  1. Check conditions early and exit if they fail, keeping your main code path clean and positive
  2. Automatically narrow types after the check, so TypeScript knows a variable is safe to use
  3. 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);
}

so if (!user) { return; } etc?

1 Like

Your problem appears to be that you're relying on using an initial check that wraps your function body rather than using early returns. Your "After" example can be written using entirely using existing syntax, in a way that many authors would immediately recognize and understand:

// After: Guards make your main path clear
function processUser(user?: User) {
  if(!user) return;
  if(!user.isActive) return;
  if(!user.permissions.includes('admin')) return;
  
  // Main logic stands out - not buried in conditionals
  doSomethingImportant(user);
}

No need for new syntax. This is even less characters, if that matters.

2 Likes