Skip to content

TypeScript - Decision Making

Conditional statements allow programs to execute different blocks of code based on whether a specific condition evaluates to true or false. These structures are fundamental for controlling the flow of execution in any program.

The basic structure involves evaluating a condition (a boolean expression). If the condition is true, one block of code executes. Optionally, if the condition is false, another block of code can be executed.

TypeScript uses conditional statements familiar to developers coming from JavaScript or other C-style languages. They work by evaluating a boolean expression:

condition ? statement_if_true : statement_if_false; // Ternary Operator
if (condition) {
// Block of code if condition is true
} else if (another_condition) {
// Block of code if another_condition is true
} else {
// Block of code if all previous conditions are false
}
switch (expression) {
case value1:
// Code to execute if expression === value1
break; // Important to prevent fall-through
case value2:
// Code to execute if expression === value2
break;
default:
// Code to execute if no case matches
}

TypeScript classifies these decision-making constructs as follows:

StatementDescription
if statementExecutes a block of code only if a specified boolean condition is true.
if…else statementExecutes one block of code if a condition is true, and another block if the condition is false.
else if statementAllows checking multiple conditions in sequence. Often used with a final else block for a default case.
Nested if statementsPlacing an if or else if statement inside another if or else if block for more complex logic.
switch statementEvaluates an expression and executes code corresponding to matching case labels. Uses strict comparison (===).
Ternary Operator (?:)A shorthand for an if...else statement, useful for conditional assignments or simple expressions.

A key feature in TypeScript related to conditional statements is Type Narrowing. When you perform checks like typeof variable === 'string' or variable instanceof MyClass within an if block, TypeScript understands that inside that block, the variable has the narrowed type. This allows you to safely access properties or methods specific to that type without compiler errors.

function processInput(input: string | number) {
if (typeof input === 'number') {
// Inside this block, TypeScript knows 'input' is a number
console.log(`Processing number: ${input.toFixed(2)}`);
} else {
// Inside this block, TypeScript knows 'input' is a string
console.log(`Processing string: ${input.toUpperCase()}`);
}
}
processInput(123.456);
processInput("hello world");

Understanding type narrowing is crucial for writing type-safe conditional logic in TypeScript, especially when dealing with union types.

  • Use strict equality (=== and !==) instead of loose equality (== and !=) to avoid unexpected type coercion.
  • Always include a break statement in switch cases unless fall-through behavior is explicitly intended and documented.
  • Use a default case in switch statements to handle unexpected values.
  • Keep conditions clear and readable. Complex conditions might be better broken down into smaller parts or helper functions.
  • Leverage type narrowing with typeof, instanceof, property checks ('prop' in obj), and custom type guards for safer code with union types.