TypeScript if…else Statement
In TypeScript, if-else statements are conditional constructs that allow developers to execute different blocks of code based on a specified condition. The basic syntax of an if-else statement in TypeScript is as follows:
Here, condition is an expression that is evaluated. If the condition is true, the code block within the first set of curly braces is executed; otherwise, the code block within the else statement is executed.
Here's an example illustrating the use of if-else statements in TypeScript:
This checks if the variable age is greater than or equal to 18. If it is, the if block prints a message about voting eligibility. Otherwise, the else block prints a message about age restriction.
Chained if-else (else if)
This checks the value of the variable grade. Depending on whether it's "A", "B", or something else, different messages are printed. This allows for handling multiple conditions in a single if-else construct.
Nested if-else
This uses nested if-else statements to check both login status and access permission. This allows for more complex decision-making based on multiple conditions.
Early exit with break
This if-else statement is used within a loop. When the variable i reaches 5, the break statement inside the if block exits the loop immediately, even though there are remaining iterations.
Type narrowing with conditional types
This example showcases how if-else can be used with TypeScript's conditional types. Based on the value of the user parameter, the type of the return value is narrowed to either true or false, making code more precise and safer.
Conclusion
TypeScript if-else statements provide a mechanism for executing different blocks of code based on a specified condition. They enable developers to create decision-making logic, allowing for the execution of specific code paths depending on whether a given condition is true or false.