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:

if (condition) { // Code to be executed if the condition is true } else { // Code to be executed if the condition is false }

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:

let age = 25; if (age >= 18) { console.log("You are eligible to vote."); } else { console.log("You are too young to vote."); }

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)

let grade = "A"; if (grade === "A") { console.log("Excellent job!"); } else if (grade === "B") { console.log("Good work!"); } else { console.log("Please try harder next time."); }

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

let isLoggedIn = true; let hasPermission = false; if (isLoggedIn) { if (hasPermission) { console.log("You can access the resource."); } else { console.log("You don't have access permission."); } } else { console.log("Please log in to access the resource."); }

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

for (let i = 0; i < 10; i++) { if (i === 5) { break; // Exits the loop when i reaches 5 } console.log(i); }

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

type UserType = "admin" "user"; function canEditPost(user: UserType): boolean { if (user === "admin") { return true; // Type narrowed to boolean with true value } else { return false; // Type narrowed to boolean with false value } }

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.