Error Handling and Validation
Guard Clauses
Guard clauses reject invalid input before the main work starts.
Guard Clauses
guards.ts
function priceLabel(cents: number): string {
if (cents < 0) {
return "invalid";
}
if (cents === 0) {
return "free";
}
return `$${(cents / 100).toFixed(2)}`;
}
const cents: number = ;
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 = ;
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 = ;
const label: string = priceLabel(cents);
console.log(`price=${label}`);
guard clause
A guard clause checks a requirement early and returns or throws before the rest of the function runs.