TypeScript Conditions — if/else, Switch & Type Guards with Playwright Examples

Conditions let you control which code runs based on different scenarios — essential for building smart Playwright tests that handle popups, dynamic content, and different environments. This guide covers if/else, switch, ternary operators, and type guards with real test automation examples.

📖 What You’ll Learn: if/else statements, else if chains, switch/case, ternary operator, type narrowing with conditions, and real Playwright conditional flows.


🔀 if / else Statement

The most basic conditional — execute code only when a condition is true.

let temperature: number = 30;

if (temperature > 25) {
  console.log("It's hot outside! ☀️");
} else {
  console.log("It's cool outside! 🌤️");
}
// Output: "It's hot outside! ☀️"

🔗 else if Chain

Check multiple conditions in sequence — the first match wins.

let score: number = 85;
let grade: string;

if (score >= 90) {
  grade = "A — Excellent!";
} else if (score >= 80) {
  grade = "B — Good job!";
} else if (score >= 70) {
  grade = "C — Average";
} else if (score >= 60) {
  grade = "D — Below average";
} else {
  grade = "F — Needs improvement";
}

console.log(grade);  // "B — Good job!"

💡 Tip: Order your conditions from most specific to least specific. TypeScript evaluates them top-to-bottom and stops at the first match.


🔄 Switch Statement

When you have many possible values for a single variable, switch is cleaner than multiple if/else statements.

type Browser = 'chromium' | 'firefox' | 'webkit';
let browserName: Browser = 'chromium';

switch (browserName) {
  case 'chromium':
    console.log('🌐 Running on Chrome/Edge');
    break;
  case 'firefox':
    console.log('🦊 Running on Firefox');
    break;
  case 'webkit':
    console.log('🧭 Running on Safari');
    break;
  default:
    console.log('❓ Unknown browser');
}

// Switch with return (in a function)
function getTimeout(env: string): number {
  switch (env) {
    case 'production': return 30000;
    case 'staging':    return 15000;
    case 'local':      return 5000;
    default:           return 10000;
  }
}

⚡ Ternary Operator

A one-liner alternative to if/else — perfect for simple conditions.

// Syntax: condition ? valueIfTrue : valueIfFalse

let isProduction: boolean = false;
let baseURL = isProduction ? 'https://app.com' : 'https://staging.app.com';

let userAge: number = 20;
let category = userAge >= 18 ? 'Adult' : 'Minor';

// Nested ternary (use sparingly!)
let speed: number = 100;
let zone = speed > 120 ? 'Danger' : speed > 80 ? 'Fast' : 'Normal';

⚠️ Avoid nested ternaries — they’re hard to read. Use if/else instead when the logic is complex.


🔍 Type Narrowing with Conditions

TypeScript gets smarter inside conditional blocks — it narrows the type automatically.

// typeof narrowing
function formatValue(value: string | number): string {
  if (typeof value === 'string') {
    return value.toUpperCase();  // TypeScript knows it's a string here
  } else {
    return value.toFixed(2);     // TypeScript knows it's a number here
  }
}

// Truthiness narrowing
function greetUser(name: string | null | undefined): string {
  if (name) {
    return 'Hello, ' + name;   // name is definitely a string here
  }
  return 'Hello, Guest';
}

// in operator narrowing
interface Dog { bark(): void; breed: string; }
interface Cat { meow(): void; color: string; }

function handlePet(pet: Dog | Cat) {
  if ('bark' in pet) {
    pet.bark();    // TypeScript knows it's a Dog
  } else {
    pet.meow();    // TypeScript knows it's a Cat
  }
}

🎭 Conditions in Playwright — Real Examples

import { test, expect } from '@playwright/test';

test('handle dynamic page content', async ({ page }) => {
  await page.goto('https://sqatools.in');
  
  // Close popup if it appears
  const popup = page.locator('.popup-overlay');
  if (await popup.isVisible({ timeout: 3000 }).catch(() => false)) {
    await popup.locator('.close-btn').click();
    console.log('Popup closed');
  }
  
  // Environment-based navigation
  const env = process.env.TEST_ENV ?? 'staging';
  switch (env) {
    case 'production':
      await page.goto('https://sqatools.in');
      break;
    case 'staging':
      await page.goto('https://staging.sqatools.in');
      break;
    default:
      await page.goto('http://localhost:3000');
  }
  
  // Conditional assertions based on page state
  const loginBtn = page.locator('#login-btn');
  const dashboardLink = page.locator('#dashboard');
  
  if (await loginBtn.isVisible()) {
    console.log('User is not logged in');
    await loginBtn.click();
  } else if (await dashboardLink.isVisible()) {
    console.log('User is already logged in');
  }
});

❓ FAQ

🤔 When should I use switch vs if/else?

Use switch when comparing a single variable against multiple specific values. Use if/else when conditions are complex expressions or involve multiple variables.


🤔 What is type narrowing in TypeScript?

Type narrowing is when TypeScript automatically narrows a union type to a more specific type inside a conditional block. For example, after if (typeof x === 'string'), TypeScript knows x is a string.

🎯 Next Steps

🎬 Watch the full TypeScript tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Leave a Comment