Day 47 of 100: Type Narrowing — Guards That Make unknown Safe
Day 47 of 100 — 100 Days of Playwright with TypeScript Challenge. Phase: TypeScript. JavaScript (Days 1-33) → TypeScript (Days 34-63) → Playwright (Days 64-96) → AI Framework Capstone (Days 97-100).
🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy.
Narrowing: turning broad types (unknown, unions) into specific ones via runtime checks the compiler understands.
Contents
Built-In Guards
function describe(value: string | number | string[]): string {
if (typeof value === 'string') return value.toUpperCase(); // string here
if (Array.isArray(value)) return value.join(','); // string[] here
return value.toFixed(2); // number left
}
🚀 Level Up Your Playwright
From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.
Custom Type Guards — is
type User = { id: number; email: string };
function isUser(v: unknown): v is User {
return (
typeof v === 'object' && v !== null &&
'id' in v && typeof (v as any).id === 'number' &&
'email' in v && typeof (v as any).email === 'string'
);
}
const body: unknown = JSON.parse('{"id":1,"email":"a@b.com"}');
if (isUser(body)) {
body.email; // fully typed — no casting
} else {
throw new Error('response is not a User');
}
Why This Is the API-Testing Pattern
- res.json() returns unknown-ish any — guards convert it to trusted types
- Guard fails → loud error at the boundary, not deep in assertions
- One isUser() guard reused across every user-endpoint test
Tomorrow (Day 48): unknown vs any — the safety line.
🎓 Master Playwright End to End
Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.
