Error Handling and Validation
Guard Clauses
Guard clauses reject invalid input before the main work starts.
guard clause
A guard clause checks a requirement early and returns or throws before the rest of the function runs.
Guard Clauses
guards.ts
Replay: real traced execution (multi-file project)
function priceLabel(cents: number): string {
if (cents < 0) {
return "invalid";
}
if (cents === 0) {
return "free";
}
return `$${(cents / 100).toFixed(2)}`;
}
const cents: number = 250;
const label: string = priceLabel(cents);
console.log(`price=${label}`);
function priceLabel(cents: number): string {
if (cents < 0) {
return "invalid";
}
if (cents === 0) {
return "free";
}
return `$${(cents / 100).toFixed(2)}`;
}
const cents: number = -1;
const label: string = priceLabel(cents);
console.log(`price=${label}`);
function priceLabel(cents: number): string {
if (cents < 0) {
return "invalid";
}
if (cents === 0) {
return "free";
}
return `$${(cents / 100).toFixed(2)}`;
}
const cents: number = 0;
const label: string = priceLabel(cents);
console.log(`price=${label}`);
cents ← 250
8 return `$${(cents / 100).toFixed(2)}`;9}1011const cents→ 250: number = 250; //@cents=-1, 012const label: string = priceLabel(cents250);function priceLabel(cents: number): string
1function priceLabel(cents250: number): string {2 if (cents < 0) {3 return "invalid";4 }5 if (cents === 0) {6 return "free";7 }8 return `$${(cents / 100).toFixed(2)}`;9}label ← $2.50
11const cents: number = 250; //@cents=-1, 012const label→ $2.50: string = priceLabel(cents250);1314console.log(`price=${label$2.50}`);outputprice=$2.50
cents ← -1
8 return `$${(cents / 100).toFixed(2)}`;9}1011const cents→ -1: number = -1;12const label: string = priceLabel(cents-1);function priceLabel(cents: number): string
1function priceLabel(cents-1: number): string {2 if (cents < 0) {if (cents < 0)
1function priceLabel(cents: number): string {2 if (cents-1 < 0) {3 return "invalid";4 }label ← invalid
11const cents: number = -1;12const label→ invalid: string = priceLabel(cents-1);1314console.log(`price=${labelinvalid}`);outputprice=invalid
cents ← 0
8 return `$${(cents / 100).toFixed(2)}`;9}1011const cents→ 0: number = 0;12const label: string = priceLabel(cents0);function priceLabel(cents: number): string
1function priceLabel(cents0: number): string {2 if (cents < 0) {if (cents === 0)
3 return "invalid";4}5if (cents0 === 0) {6 return "free";7}label ← free
11const cents: number = 0;12const label→ free: string = priceLabel(cents0);1314console.log(`price=${labelfree}`);outputprice=free