Typescript control flow
Created By: chatGPT
In TypeScript, control flow refers to the order in which the code executes. It's essential for making decisions, handling different paths, and managing logic. The primary control flow structures in TypeScript include if statements, switch statements, for loops, and while loops. Each of these structures has its own syntax and use cases, allowing you to create more dynamic and responsive code. Below are examples of these control flow mechanisms:
If Statement: An
if
statement executes a block of code if the specified condition is true. You can also use else if
and else
to create conditional branches.let num: number = 10;
if (num > 0) {
console.log('Positive number');
} else if (num < 0) {
console.log('Negative number');
} else {
console.log('Zero');
}
Switch Statement: A
switch
statement is another way to conduct multi-way branching. It compares a variable against several values (cases) and executes the appropriate block of code.let fruit: string = 'apple';
switch (fruit) {
case 'apple':
console.log('Apple selected');
break;
case 'banana':
console.log('Banana selected');
break;
default:
console.log('Unknown fruit');
}
For Loop: A
for
loop is used to execute a block of code a specific number of times. It consists of an initialization, a condition, and an increment/decrement expression.for (let i: number = 0; i < 5; i++) {
console.log('Iteration: ' + i);
}
While Loop: A
while
loop continues to execute the block of code as long as the specified condition is true. It's useful when the number of iterations is not known beforehand.let count: number = 0;
while (count < 5) {
console.log('Count: ' + count);
count++;
}
To enhance control flow, TypeScript allows the use of type guards, which help in narrowing down types within conditionals. This feature is beneficial when working with union types and ensures types are handled correctly throughout your code base. Here's an example:
Understanding these control flow structures will enable you to write more efficient and assessable TypeScript code, making your applications more responsive to different situations. Experimenting with each of these constructs can help in grasping their unique behavior and potential.function process(value: number | string) {
if (typeof value === 'string') {
console.log('This is a string: ' + value);
} else {
console.log('This is a number: ' + value);
}
}
process('Hello');
process(42);