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