Chapter 25: Union types and narrowing
Automation learning lab
Playwright Automation
Self Study Guide
Start from zero. Learn JavaScript and TypeScript, automate browsers, and build reliable end-to-end tests.
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
- Define a union
- Check typeof
- Use a type-specific operation
Example
function show(value: string | number) {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value.toFixed(1);
}
console.log(show('qa'), show(3));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
60-chapter learning path
Start at chapter 1, or choose any topic. Your progress is tracked separately for each chapter.
JavaScript fundamentals
TypeScript fundamentals
Playwright • setup & locators
Playwright • interactions & assertions
Playwright • framework & debugging
Playwright • real-world automation
Interactive practice lab
Try the controls below and observe the corresponding Playwright locator instructions. This browser demo does not execute Node.js or Playwright Test; copy the code to your local Playwright project to automate it.
Task manager demo
Suggested automation
Actions on the demo update these examples. In your local test use a page that contains the same controls.
Download a standalone lab page, then serve it locally (for example with Python's http.server). Navigate to it in a Playwright test.