Intermediate Type Safety
Now that you know the basics, let's look at the concepts you will use every day when building automation frameworks.
1. Aliases & Interfaces
Interfaces define the exact "shape" of an object. This is critical for typing API payloads or Page Object models.
typescript
// Defining an Interface
interface User {
id: number;
name: string;
isActive: boolean;
}
// Using the Interface
const testUser: User = {
id: 101,
name: "QA Automation Engineer",
isActive: true
};
console.log(Logging in as ${testUser.name});
2. Union Types
Union types allow a variable to be one of multiple types. Very common in Playwright when an element might exist or might be null.
typescript
// The value can be a string OR null
let currentUrl: string | null = "https://example.com";
if (currentUrl !== null) {
console.log(Navigating to ${currentUrl});
} else {
console.log("No URL provided, skipping test.");
}
3. Functions
Typing the input parameters and the return value ensures your helper methods are always used correctly.
typescript
// A function that takes a string and returns a boolean
function validateLogin(username: string): boolean {
if (username === "admin") {
return true;
}
return false;
}
const isSuccess = validateLogin("admin");
console.log(Login validation passed: ${isSuccess});
4. Classes (OOP)
Classes are blueprints for creating objects. This is the absolute backbone of the Page Object Model (POM) architecture in Playwright frameworks.
typescript
class LoginPage {
readonly url: string;
constructor() {
this.url = "https://myapp.com/login";
}
async navigate() {
console.log(Navigating to ${this.url});
// await page.goto(this.url);
}
}
const loginPage = new LoginPage();
loginPage.navigate();
5. Literal Types & Enums
Literal types specify the *exact* value a string can hold. Used heavily for defining browser names or environments.
typescript
// Literal Type
type BrowserType = 'chromium' | 'firefox' | 'webkit';
let myBrowser: BrowserType = 'chromium';
// myBrowser = 'ie'; // TS ERROR! 'ie' is not allowed!
console.log(Running tests on ${myBrowser});
6. Null & Error Handling
When a script interacts with a browser, things can predictably go wrong. If you don't handle these errors, your entire test suite crashes.
typescript
const expectedElement: string | null = null; // Simulating a missing element
try {
if (expectedElement === null) {
throw new Error("Element not found on the page!");
}
console.log("Successfully clicked the element.");
} catch (error: any) {
console.log(β οΈ Handled Exception: ${error.message});
console.log("Taking a backup screenshot...");
}