|

Day 41 of 100: Generics — One Helper, Every Type

Day 41 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.


Generics: write a function once, use it with any type, keep full type safety. The you see everywhere.

Contents

The Problem and the Fix

// Without generics — either duplicate or lose types:
function firstAny(arr: any[]): any { return arr[0]; }   // type info gone

// Generic — T flows through:
function first(arr: T[]): T | undefined {
  return arr[0];
}

const n = first([1, 2, 3]);          // n: number | undefined
const s = first(['a', 'b']);         // s: string | undefined — inferred!

🚀 Level Up Your Playwright

From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.

QA Generic: Typed API Wrapper

type User = { id: number; name: string };
type Order = { id: number; total: number };

async function getJson(url: string): Promise {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`${res.status} from ${url}`);
  return res.json() as Promise;
}

const user = await getJson('/api/users/1');
user.name;            // autocompleted, type-checked
const order = await getJson('/api/orders/9');
order.total;          // number — one wrapper, every endpoint

Generic Test Data Factory

function buildList(make: (i: number) => T, count: number): T[] {
  return Array.from({ length: count }, (_, i) => make(i));
}

const users = buildList(i => ({ id: i, name: `user-${i}` }), 5);
// users: { id: number; name: string }[]

Tomorrow (Day 42): Generic constraints — narrowing what T can be.

🎓 Master Playwright End to End

Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.