TypeScript Conditional Statements
Conditional statements are used to execute different code blocks based on different conditions. TypeScript supports the same conditional statements as JavaScript.
1. if Statement
The if statement is the most basic conditional control structure. It executes a code block when the specified condition is true.
Syntax
Example
2. if...else Statement
The if...else statement executes one code block when the condition is true and another code block when the condition is false.
Syntax
Example
3. if...else if...else Statement
When you need to check multiple conditions, you can use the if...else if...else structure. It tests each condition in order and executes the code block corresponding to the first condition that is true.
Syntax
Example
4. switch Statement
The switch statement is used to execute one of multiple code blocks based on the value of an expression. It's typically used as an alternative to if...else if...else statements, especially when all conditions depend on the value of the same variable.
Syntax
- The
breakkeyword is required. It terminates the execution of theswitchstatement. Ifbreakis omitted, code will continue executing the nextcase, which is called "fall-through." - The
defaultclause is optional and used to handle all other cases.