TestingDocs.com logoTestingDocs.com
Automation learning lab
TestingDocs • Self-paced course

Playwright Automation
Self Study Guide

Start from zero. Learn JavaScript and TypeScript, automate browsers, and build reliable end-to-end tests.

60 chaptersBeginner friendlyHands-on practice
TypeScript / Chapter 25 of 60~12 min • Beginner
Chapter 25TypeScript

Union types and narrowing

A union allows more than one possible type. Narrowing uses checks such as typeof or a discriminant to determine which operations are safe. This is helpful when a test configuration accepts multiple kinds of inputs.

How it works

Step-by-step walkthrough

  1. Define a union
  2. Check typeof
  3. Use a type-specific operation

Example

TypeScript
function show(value: string | number) {
  if (typeof value === 'string') {
    return value.toUpperCase();
  }
  return value.toFixed(1);
}
console.log(show('qa'), show(3));
Expected result: QA 3.0
💡 Point to remember
Do not force a type assertion when a real check is possible.

✎ Your practice task

Add a boolean alternative and narrow it.

Knowledge check

Which operator can narrow a primitive union?

🌐 Continue learning