Playwright + TS · Lesson 11 of 36
Module 11: TypeScript for Test Automation
Try it yourself
Complete the UserProfile interface and buildAuthHeader function:
Bearer ${user.token} } or throws if token is missing.The editor has a worked example. Read it, tweak it, then press Mark as complete.
In this lesson
In dynamic languages like JavaScript or Python, changing a field name in an API or form from user_email to userEmail causes dozens of runtime errors deep in your test runs. In TypeScript, your editor catches this instantly before you even trigger a browser session.
Define strict contracts for test payloads:
export interface UserCredentials {
readonly email: string;
readonly passwordHash: string;
readonly role: "ADMIN" | "QA" | "VIEWER";
readonly rememberMe?: boolean;
}
export interface ApiResponse<T> {
status: number;
message: string;
data: T;
}Never hardcode URLs or magic timeouts inside tests:
export const TIMEOUTS = {
SHORT: 5_000,
MEDIUM: 15_000,
LONG: 30_000,
} as const;
export interface EnvironmentConfig {
baseUrl: string;
apiUrl: string;
defaultTimeout: number;
}
export const ENV_CONFIG: Record<string, EnvironmentConfig> = {
staging: {
baseUrl: "https://staging.targetqa.com",
apiUrl: "https://api.staging.targetqa.com",
defaultTimeout: TIMEOUTS.MEDIUM,
},
production: {
baseUrl: "https://targetqa.com",
apiUrl: "https://api.targetqa.com",
defaultTimeout: TIMEOUTS.LONG,
},
};Group reusable actions and domain concepts into strongly typed utility classes:
export class StringFormatter {
public static extractOrderId(text: string): string {
const match = text.match(/Order #(\d+)/);
if (!match) throw new Error(`Failed to parse Order ID from text: ${text}`);
return match[1];
}
}Welcome to Phase 2! Here we connect TypeScript directly with test automation. In this lesson, you will learn how to design type-safe test data interfaces, centralized configuration objects, constants, and utility classes. This compile-time safety prevents silent test bugs and makes your framework robust. Let's get started!
Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.
'as const' turns object properties into readonly literal types rather than generic strings or numbers, enabling TypeScript to enforce exact values.
Always prefer typed objects or domain interfaces. Returning typed objects ensures any test reading data from a page method gets full auto-completion and compile-time verification.
Finished reading?
Review the worked example in the editor, then mark the lesson complete.