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

✎ Practise what you learned: 30 TypeScript conditions programs with solutions →

TypeScript Operators β€” Complete Guide with Playwright Examples

Operators are the building blocks of every TypeScript program. Whether you’re writing Playwright test automation or building applications, understanding operators is essential. This guide covers every operator type in TypeScript with practical examples you can use in your Playwright projects.

πŸ“– What You’ll Learn: Arithmetic, Comparison, Logical, Assignment, Ternary, Nullish Coalescing, and Type operators β€” all with real Playwright examples.


βž• Arithmetic Operators

Arithmetic operators perform mathematical calculations on numbers.

let a: number = 10;
let b: number = 3;

console.log(a + b);   // 13  β€” Addition
console.log(a - b);   // 7   β€” Subtraction
console.log(a * b);   // 30  β€” Multiplication
console.log(a / b);   // 3.33 β€” Division
console.log(a % b);   // 1   β€” Modulus (remainder)
console.log(a ** b);  // 1000 β€” Exponentiation

// Increment and Decrement
let count: number = 5;
count++;   // 6 (post-increment)
count--;   // 5 (post-decrement)
++count;   // 6 (pre-increment)

βš–οΈ Comparison Operators

Comparison operators compare two values and return a boolean (true or false). These are essential in Playwright assertions.

let x: number = 5;
let y: string = "5";

// Loose equality (compares value only, allows type coercion)
console.log(x == y);    // true β€” NOT recommended in TypeScript

// Strict equality (compares value AND type)
console.log(x === 5);   // true β€” ALWAYS use this
console.log(x === y);   // Error! TypeScript catches this at compile time

// Not equal
console.log(x != y);    // false (loose)
console.log(x !== 10);  // true (strict)

// Greater / Less than
console.log(x > 3);     // true
console.log(x >= 5);    // true
console.log(x < 10);    // true
console.log(x <= 4);    // false

⚠️ Golden Rule: Always use === (strict equality) and !== in TypeScript. The loose operators == and != can cause subtle bugs that are hard to debug in test automation.


🧠 Logical Operators

Logical operators combine multiple conditions. You'll use these constantly in test automation for complex validations.

let isLoggedIn: boolean = true;
let isAdmin: boolean = false;
let hasPermission: boolean = true;

// AND (&&) β€” ALL conditions must be true
console.log(isLoggedIn && isAdmin);         // false
console.log(isLoggedIn && hasPermission);    // true

// OR (||) β€” at least ONE must be true
console.log(isAdmin || hasPermission);       // true

// NOT (!) β€” reverses the boolean
console.log(!isLoggedIn);                    // false
console.log(!isAdmin);                       // true

// Combining multiple operators
if (isLoggedIn && (isAdmin || hasPermission)) {
  console.log("Access granted");  // This runs
}

πŸ“ Assignment Operators

let num: number = 10;

num += 5;   // num = num + 5  β†’ 15
num -= 3;   // num = num - 3  β†’ 12
num *= 2;   // num = num * 2  β†’ 24
num /= 4;   // num = num / 4  β†’ 6
num %= 4;   // num = num % 4  β†’ 2
num **= 3;  // num = num ** 3 β†’ 8

❓ Ternary & Nullish Coalescing Operators

These are shorthand operators that make your code cleaner and more readable.

// Ternary Operator: condition ? valueIfTrue : valueIfFalse
let age: number = 20;
let status: string = age >= 18 ? "Adult" : "Minor";
console.log(status);  // "Adult"

// Nullish Coalescing (??) β€” returns right side if left is null/undefined
let username: string | null = null;
let displayName = username ?? "Guest";
console.log(displayName);  // "Guest"

// Optional Chaining (?.) β€” safely access nested properties
interface User {
  name: string;
  address?: { city?: string };
}
let user: User = { name: "Deepesh" };
console.log(user.address?.city);  // undefined (no error!)

πŸ” Type Operators (TypeScript-Specific)

// typeof β€” check runtime type
let value: unknown = "hello";
if (typeof value === "string") {
  console.log(value.toUpperCase());  // "HELLO"
}

// instanceof β€” check if object is an instance of a class
class Animal { name: string = "dog"; }
class Dog extends Animal { breed: string = "lab"; }

let pet = new Dog();
console.log(pet instanceof Dog);     // true
console.log(pet instanceof Animal);  // true

// keyof β€” get union of object keys (compile-time only)
interface Config {
  baseURL: string;
  timeout: number;
}
type ConfigKey = keyof Config;  // "baseURL" | "timeout"

// as β€” type assertion
let someValue: unknown = "this is a string";
let strLength: number = (someValue as string).length;

🎭 Operators in Playwright β€” Real Examples

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

test('using operators in Playwright tests', async ({ page }) => {
  await page.goto('https://sqatools.in');
  
  // Comparison: check element count
  const links = await page.locator('a').count();
  expect(links > 0).toBeTruthy();
  
  // Logical: multiple conditions
  const title = await page.title();
  const isCorrectPage = title.includes('SQA') && links > 10;
  expect(isCorrectPage).toBe(true);
  
  // Nullish coalescing: safe text extraction
  const headerText = await page.locator('h1').first().textContent() ?? '';
  expect(headerText.length > 0).toBeTruthy();
  
  // Ternary: conditional actions
  const env = process.env.ENV ?? 'staging';
  const timeout = env === 'production' ? 30000 : 10000;
  
  // typeof: type guards for safe handling
  const attribute = await page.locator('body').getAttribute('class');
  if (typeof attribute === 'string') {
    console.log('Body classes:', attribute);
  }
});

❓ FAQ

πŸ€” What is the difference between == and === in TypeScript?

== compares values with type coercion (loose equality), while === compares both value and type (strict equality). Always use === in TypeScript.


πŸ€” What is the nullish coalescing operator (??) in TypeScript?

The ?? operator returns the right-hand value when the left-hand value is null or undefined. Unlike ||, it doesn't treat 0, "", or false as "empty".


πŸ€” How do I use typeof in Playwright tests?

Use typeof to check the runtime type of values returned from page methods. For example, typeof (await page.title()) === 'string' ensures you're working with a string before calling string methods.

🎯 Next Steps

Now that you understand TypeScript operators, continue your learning journey:

🎬 Watch the full TypeScript tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

✎ Practise what you learned: 30 TypeScript operators programs with solutions →