Back to cheat sheet hub

TypeScript Cheat Sheet

A focused TypeScript reference for automation engineers who want safer Playwright code, typed utilities, and cleaner collaboration.

Types and interfaces Narrowing Generics and utility types

Basic Types

TypeScript adds compile-time safety so mistakes are caught before tests run.

const course: string = 'Playwright';
const score: number = 92;
const isActive: boolean = true;
const tags: string[] = ['ui', 'api', 'regression'];

Interfaces and Type Aliases

Use interfaces for objects you share across tests, fixtures, or API helpers.

interface StudentProfile {
  id: string;
  name: string;
  githubUsername?: string;
  points: number;
}

type Difficulty = 'easy' | 'medium' | 'hard';

Functions

Typed function signatures make helper behavior explicit and easier to reuse.

function addPoints(current: number, extra: number): number {
  return current + extra;
}

const formatRank = (rank: number): string => `#${rank}`;

Unions and Narrowing

Unions let values be flexible while still remaining safe after checks.

function printValue(value: string | number) {
  if (typeof value === 'string') {
    return value.toUpperCase();
  }

  return value.toFixed(2);
}

Optional and Readonly

Optional fields help with partial data. Readonly fields protect stable values.

interface LeaderboardUser {
  readonly id: string;
  displayName?: string;
  points: number;
}

Generics

Generics keep helpers reusable while preserving exact types.

function firstItem<T>(items: T[]): T | undefined {
  return items[0];
}

const firstScore = firstItem<number>([10, 20, 30]);

Utility Types

These are useful in API work, forms, and partial update flows.

type StudentPreview = Pick<StudentProfile, 'id' | 'name'>;
type StudentPatch = Partial<StudentProfile>;
type StudentRecord = Record<string, StudentProfile>;

Typed Async Code

Return explicit promise types from async helpers when the data matters downstream.

async function fetchProfile(id: string): Promise<StudentProfile> {
  const response = await fetch(`/api/profile/${id}`);
  return response.json();
}

Typed Playwright Fixtures

Use fixture typing when extending Playwright’s test context.

import { test as base, Page } from '@playwright/test';

type Fixtures = {
  adminPage: Page;
};

export const test = base.extend<Fixtures>({
  adminPage: async ({ browser }, use) => {
    const page = await browser.newPage();
    await use(page);
    await page.close();
  },
});