TypeScript Conditionals

if / else if / else

Basic Structure

if (condition) {
    // code block
} else if (condition) {
    // code block
} ... else {
    // code block
}

Example

let score = 82;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else {
  console.log("Grade: C or below");
}

Use braces for all conditional blocks to maintain clarity and prevent logic errors.

Ternary Operator

This syntax is ideal for simple conditions used in assignments or output.

let isLoggedIn = true;
let greeting = isLoggedIn ? "Welcome back!" : "Please log in.";

console.log(greeting);

switch Statement

switch is best used when comparing a single value against multiple known options.

let color = "blue";

switch (color) {
  case "red":
    console.log("Stop");
    break;
  case "green":
    console.log("Go");
    break;
  case "blue":
    console.log("Calm");
    break;
  default:
    console.log("Unknown color");
}

Type Narrowing in Conditionals

TypeScript uses control flow analysis to automatically narrow the type within the block, improving safety.

function printLength(value: string | null) {
  if (value !== null) {
    console.log(value.length); // Safe access
    }
    }

Best Practices

  • Use meaningful comparisons and avoid magic numbers or string literals.
  • Keep conditions clean and readable by using helper functions if necessary.
  • Always cover all cases explicitly to avoid unpredictable behavior.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic