Guard Clauses
What
A guard clause is an early return or throw statement at the beginning of a function that handles “invalid” or “empty” cases.
How
By returning early when a value is null or undefined, you narrow the type for the remainder of the function:
function process(name: string | null) {
if (!name) return ""; // Guard clause
// name is now guaranteed to be a string
return name.toUpperCase();
}
Why
Guard clauses reduce nested logic (the “Pyramid of Doom”) and keep the “happy path” of your function clean and focused. They also ensure that the core logic of your function only ever works with the narrowest, most reliable types.
Summary
Use guard clauses to strip away undesirable types early and keep your main logic simple.