Typescript Switch case tutorial(examples)
- Admin
- Feb 24, 2024
- Typescript
TypeScript Switch Class: Learn with Examples This post covers the syntax of the switch case statement with examples.
TypeScript Switch Case
The switch case
is a conditional expression that checks and evaluates the expression. When a matched case is found, the corresponding code block executes. It is used to simplify code compared to multiple if and else
conditional expressions.
Here is a switch case example
switch (conditionalExpression) {
case valueExpression1:
// body statements
// code block
break;
case valueExpression2:
// body statements
// code block
break;
default:
// body statements
// code block
break;
}
Conditional Expression::
- The
switch
statement evaluates the conditional expression value to find the matching case. Case Block
: The code inside thecase block
executes when the Conditional Expression matches with the case block.Default Block
: This code block executes when the Conditional Expression does not match any of the case blocks.- The
break
keyword is used to exit from the current case block; it is optional. - If
break
is omitted, the remaining case blocks execute after the matched case statement.
Here is a TypeScript switch case example.
Here Single case
statement is used and the default
is used if none of the cases are matched.
let value = "a";
switch (value) {
case "a":
console.log("Letter a Checked");
break;
case "b":
console.log("Letter b Checked");
break;
default:
console.log("Default letter Checked");
}
Output:
Letter a Checked
TypeScript Multiple Switch Cases Statement Example
Multiple cases can be placed for a single code block.
Here is an example of this
let value = "c";
switch (value) {
case "a":
console.log("Letter a Checked");
break;
case "b":
case "c":
case "d":
console.log("Letter b, c, and d Checked");
break;
default:
console.log("Default letter Checked");
break;
}
Output:
Letter b,c, and d Checked
TypeScript Switch Case Enum Example
Switch expressions can contain strings and numbers. However, expressions are declared with constants.
Enum constants are defined as switch expressions as well as in multiple case blocks.
Here is an example for the switch enum case:
enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY,
}
function isWorkingDay(day: Day) {
switch (day) {
case Day.SUNDAY:
console.log("Holiday");
break;
default:
console.log("Working day");
break;
}
}
const tuesday = Day.TUESDAY;
const sunday = Day.SUNDAY;
isWorkingDay(tuesday); // Working day
isWorkingDay(sunday); // Holiday
Output:
working day
holiday
String Variable in Switch and Case Example
Strings and case statements accept variables and data of string type. The value type should be a primitive string
, not the global object String
type.
Important points in the example below.
- Switch expression accepts variables of string data type.
- In each case, the value type is a string.
- Each case returns a value.
- Each case has a break statement to exit from the loop.
class SwitchExample {
public isWorkingDay(weekName: string): boolean {
switch (weekName) {
case "saturday":
console.log("Saturday");
return false;
case "sunday":
console.log("Sunday");
return false;
default:
console.log("Working day");
return true;
}
}
}
let example = new SwitchExample();
console.log(example.isWorkingDay("sunday"));
console.log(example.isWorkingDay("monday"));
output
Sunday
false
working day
true
Primitive Data Type Values in Switch Case
Switch cases accept primitive types of numbers as well as expressions.
Below is an example to check if a given number is positive or negative using a TypeScript switch case.
The expression accepts a conditional expression which returns true
or false
. Each case block must be provided with a Boolean value.
class SwitchNumberExample {
public isPositive(value: number): boolean {
switch (value < 0) {
case false:
console.log("negative number");
return false;
break;
default:
console.log("positive number");
return true;
break;
}
}
}
var example = new SwitchNumberExample();
console.log(example.isPositive(1));
console.log(example.isPositive(-1));
Here is an output
negative number
false
positive number
true
How to Check Properties of an Object Using Switch
interface Employee {
department: string;
name: string;
}
let employee: Employee = { department: "sales", name: "Eric" };
switch (employee.department) {
case "sales":
console.log(`${employee.name} department is ${employee.department} `);
break;
case "marketing":
console.log(`${employee.name} department is ${employee.department} `);
break;
default:
console.log("Department Not found.");
}
Switch Case Union Type with Object and Interface
The example below uses the following.
- Created marker interfaces that have no methods.
- Provided classes for Animals and Lion by implementing Animal.
- Each class has a discriminator type.
- Switch case accepts a union type of Dog and Lion.
- Union type expression is evaluated against the string type case value.
interface Animal {}
class Dog implements Animal {
type: string = "dog";
}
class Lion implements Animal {
type: string = "lion";
}
class SwitchClassExample {
public getAnimal(animal: Dog | Lion) {
switch (animal.type) {
case "dog":
console.log("Animal is Dog");
break;
case "lion":
console.log("Animal is Lion");
break;
default:
console.log("Other Animal types");
break;
}
}
}
let example = new SwitchClassExample();
let animal = new Dog();
example.getAnimal(animal);
example.getAnimal(new Lion());
and given output:
Animal is Dog
Animal is Lion
TypeScript Configuration - noFallthroughCasesInSwitch
The noFallthroughCasesInSwitch
value is Boolean, i.e., true or false.
tsconfig.json
contains this configuration in a TypeScript application.
It returns an error for fall-through switch cases.
Following is the switch case fall-through example, where there are no break statements.
If noFallthroughCasesInSwitch
=true, the below case is not allowed:
switch (value) {
case 1:
// statements
case 2:
// statements 2
}
Conclusion
This tutorial covers TypeScript switch
case syntax and multiple expression enum
break examples. Additionally, it addresses the TypeScript configuration noFallthroughCasesInSwitch
.