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.ts234 chars9 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.ts225 chars9 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