how to use guard statement in typescript

In TypeScript, a guard statement is a conditional statement that checks whether a certain condition is true or not. It's typically used to handle error cases and exit early from a function or block of code.

Here's an example of using a guard statement in TypeScript:

index.ts
function calculateArea(radius: number): number {
  if (radius < 0) {
    console.error("Invalid argument: radius cannot be negative");
    return -1; // use -1 to indicate an error condition
  }

  return Math.PI * radius * radius;
}
234 chars
9 lines

In the above example, the guard statement checks if the radius argument is less than zero, which would be an invalid value for calculating the area of a circle. If the condition is true, an error message is printed to the console and -1 is returned to indicate an error condition. If the condition is false, the function calculates and returns the area of the circle as expected.

Guard statements can also be used with more complex conditions, like checking for the presence of a property in an object:

index.ts
function greetPerson(person: { name?: string; age?: number }): void {
  if (!person.name) {
    console.error("Invalid argument: person must have a name property");
    return;
  }

  console.log(`Hello, ${person.name}!`);
}
225 chars
9 lines

In the above example, the guard statement checks if the name property exists in the person object. If it doesn't, an error message is printed to the console and the function exits early. If the property exists, the function greets the person by name as expected.

Overall, guard statements are a useful tool for writing more robust and error-resistant code in TypeScript.

gistlibby LogSnag