Conditional Statements in TypeScript

Conditional Statements in TypeScript

In this article, we will explain conditional statements in TypeScript.

YouTube Video

If Statements in TypeScript

In TypeScript, an if statement performs branching that executes code if a specified condition is true and does not execute it if the condition is false. The if statement has the same syntax as in JavaScript and uses TypeScript's type safety to perform conditional branching.

Basic Syntax

The basic syntax of the if statement is as follows.

1if (condition) {
2    // Code to execute if the condition is true
3} else if (anotherCondition) {
4    // Code to execute if the first condition is false
5    // and the another condition is true
6} else {
7    // Code to execute if all conditions are false
8}
  • If condition is true, the code in the following block is executed.
  • If condition is false and anotherCondition is true, the code in the following block is executed.
  • If none of the conditions are true, the code in the final else block is executed.

Example 1: Basic if-else Statement

In the following example, it checks whether the variable x is 10 or greater and outputs the result.

1let x: number = 15;
2
3if (x >= 10) {
4    console.log("x is 10 or greater");
5} else {
6    console.log("x is less than 10");
7}
8// Outputs: x is 10 or greater

Example 2: if-else if-else Statement

To check multiple conditions, use else if to add branches.

 1let score: number = 85;
 2
 3if (score >= 90) {
 4    console.log("Excellent");
 5} else if (score >= 70) {
 6    console.log("Passed");
 7} else {
 8    console.log("Failed");
 9}
10// Outputs: Passed

Example 3: if statement with type checking

It's also possible to perform conditional branching for specific types using TypeScript's type checking feature. For example, check the type of a variable with the typeof operator and perform appropriate processing.

 1let value: any = "Hello";
 2
 3if (typeof value === "string") {
 4    console.log("The value is a string: " + value);
 5} else if (typeof value === "number") {
 6    console.log("The value is a number: " + value);
 7} else {
 8    console.log("The value is of another type");
 9}
10// Outputs: "The value is a string: Hello"

Example 4: Nested if Statements

You can also nest if statements to check complex conditions.

 1let age: number = 25;
 2let isMember: boolean = true;
 3
 4if (age >= 18) {
 5    if (isMember) {
 6        console.log("You are a member and 18 years old or older");
 7    } else {
 8        console.log("You are not a member but 18 years old or older");
 9    }
10} else {
11    console.log("You are under 18 years old");
12}
13// Output
14// You are a member and 18 years old or older

Ternary operator (conditional operator)

Syntax

1condition ? valueIfTrue : valueIfFalse

If you want to write an if statement more concisely, you can use the ternary operator.

Example

1const number: number = 7;
2const result: string = number % 2 === 0 ? "Even" : "Odd";
3console.log(result); // "Odd"

In this case, since number is 7, Odd will be displayed.

Summary

  • The if statement is a fundamental control structure for determining which processing to execute based on conditions.
  • You can handle multiple conditions using else if.
  • By using typeof, you can leverage TypeScript's types for conditional branching.
  • Complex condition handling is possible with nested if statements.
  • You can also use the ternary operator to write conditional branches concisely.

In TypeScript, using if statements with type safety in mind can improve code reliability.

Switch Statements in TypeScript

The switch statement in TypeScript is a control structure used to branch code based on multiple conditions. Instead of using if-else if statements to evaluate multiple conditions, you can use a switch statement to concisely write branching logic based on specific values.

Basic Syntax

 1switch (expressionToEvaluate) {
 2    case value1:
 3        // Code to execute if the expression evaluates to value1
 4        break;
 5    case value2:
 6        // Code to execute if the expression evaluates to value2
 7        break;
 8    default:
 9        // Code to execute if none of the conditions match
10}

In a switch statement, if the value specified in a case matches the evaluated expression, the case block is executed. Be careful that if there is no break, the next case block is executed consecutively. The default block is executed if none of the case statements match.

Example 1: Basic switch Statement

In the example below, a number representing a day of the week (0 to 6) is given, and the corresponding day name is output based on that value.

 1let day: number = 3;
 2
 3switch (day) {
 4    case 0:
 5        console.log("Sunday");
 6        break;
 7    case 1:
 8        console.log("Monday");
 9        break;
10    case 2:
11        console.log("Tuesday");
12        break;
13    case 3:
14        console.log("Wednesday");
15        break;
16    case 4:
17        console.log("Thursday");
18        break;
19    case 5:
20        console.log("Friday");
21        break;
22    case 6:
23        console.log("Saturday");
24        break;
25    default:
26        console.log("Invalid day");
27}
28// Outputs: Wednesday

Example 2: Example using default

default is useful because it runs when none of the case statements match, allowing you to handle unexpected values.

 1let statusText: string = "pending";
 2
 3switch (statusText) {
 4    case "success":
 5        console.log("Operation succeeded");
 6        break;
 7    case "error":
 8        console.log("An error occurred");
 9        break;
10    case "pending":
11        console.log("Processing");
12        break;
13    default:
14        console.log("Unknown status");
15}
16// Outputs: Processing

Example 3: Executing the same process for multiple cases

If you want to perform the same action for multiple case statements, you can list them consecutively.

 1let fruit: string = "apple";
 2
 3switch (fruit) {
 4    case "apple":
 5    case "banana":
 6    case "orange":
 7        console.log("This is a fruit");
 8        break;
 9    default:
10        console.log("This is not a fruit");
11}
12// Outputs: This is a fruit

Example 4: Behavior when break is omitted

Omitting a break results in a "fall-through" behavior where the next case is also executed.

 1let rank: number = 1;
 2
 3switch (rank) {
 4    case 1:
 5        console.log("Gold");
 6    case 2:
 7        console.log("Silver");
 8    case 3:
 9        console.log("Bronze");
10    default:
11        console.log("Not ranked");
12}
13// Outputs:
14// Gold
15// Silver
16// Bronze
17// Not ranked

In this way, after a case matches, the next case is also executed, so a break is usually used to prevent unnecessary fall-through.

Summary

  • The switch statement is a control structure that allows you to write branching logic based on multiple conditions concisely.
  • Each case should explicitly terminate the process using break.
  • The default block is executed if none of the cases match.
  • It is also possible to perform the same operation for multiple cases.

The switch statement in TypeScript is useful for efficiently handling multiple conditions while maintaining code readability.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video