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'];
A focused TypeScript reference for automation engineers who want safer Playwright code, typed utilities, and cleaner collaboration.
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'];
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';
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 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 fields help with partial data. Readonly fields protect stable values.
interface LeaderboardUser {
readonly id: string;
displayName?: string;
points: number;
}
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]);
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>;
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();
}
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();
},
});