Day 49 of 100: Type Assertions — as, and When Casting Lies
Day 49 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.
as tells the compiler ‘trust me’. Sometimes necessary, often a lie waiting to fail. Know the legitimate uses.
Contents
Legitimate Uses
// 1. You genuinely know more than the compiler:
const input = document.querySelector('#email') as HTMLInputElement | null;
// 2. as const — literal freezing (not a lie, a hint):
const ROLES = ['admin', 'viewer'] as const;
type Role = typeof ROLES[number]; // 'admin' | 'viewer'
// 3. Test mocks — building partial doubles:
type Page = { goto(u: string): Promise; click(s: string): Promise };
const fakePage = { goto: async () => {} } as unknown as Page;
// double-cast acknowledged as deliberate for a mock
🚀 Level Up Your Playwright
From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.
The Lies
type User = { id: number; email: string };
const body = JSON.parse('{"id":"oops"}') as User; // compiles!
body.id.toFixed(2); // runtime crash — id is a string
// The cast silenced the exact check that would have caught this.
// Day 47 guards are the honest alternative.
Rules
- Prefer guards over casts at data boundaries
- as unknown as X signals ‘deliberate mock’ — acceptable in test doubles
- Never cast API responses directly to business types
- satisfies (Day 50 tsconfig era) checks without widening — often better
Tomorrow (Day 50): tsconfig deep dive — strict mode for test projects.
🎓 Master Playwright End to End
Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.
