Playwright + TS · Lesson 4 of 36

0/36 done

Module 4: TypeScript Fundamentals

4. Static Types, Interfaces & Type Aliases

14 minlesson

Your task

Define an interface BrowserSession with:

  • browser: of type "chromium" | "firefox" | "webkit"
  • headless: boolean
  • viewportWidth?: optional number

Write it in the editor, then press Check answer (Ctrl + Enter).

Core TypeScript Types

  • Primitives: string, number, boolean
  • Special: void (functions returning nothing), any (disables type checking - avoid!), unknown (type-safe any)

Union & Literal Types

typescript
// Literal union type: only these 3 strings are allowed!
type BrowserName = "chromium" | "firefox" | "webkit";

// Union type:
type LocatorTarget = string | number;

Interfaces vs Type Aliases

In automation frameworks, we use interfaces for object shapes (test configs, page models):

typescript
interface TestConfig {
  baseUrl: string;
  timeout?: number;        // Optional property (indicated by ?)
  readonly retries: number; // Cannot be reassigned after creation
}

Type Assertions (as)

When you know more about a value's type than TypeScript does:

typescript
const responseData = (rawJson as { token: string }).token;

Key Takeaways & Walkthrough Summary

Welcome to TypeScript! TypeScript adds static typing to JavaScript, which means your editor can catch misspelled locators, missing parameters, and type errors before your tests even run. In this lesson, we will explore explicit types, union types, interfaces, and type assertions. Let's start typing!

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.

Common Doubts & Lesson Q&A

Why should we avoid 'any' in test automation?

Using 'any' disables TypeScript's type checker entirely. If an API property name changes, 'any' prevents TypeScript from warning you, causing tests to fail at runtime instead.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

TypeScript
Skip