How to Organize TypeScript Types in a Playwright Project


Organizing TypeScript types in a Playwright project means storing reusable data definitions, interfaces, and type aliases in places where developers can easily find and maintain them.

In a small playwright automation project, you might only have a few tests. As the project grows, you may add login tests, shopping cart tests, API tests, Page Objects, and custom fixtures. Many of these files need the same types.

If you create a separate copy of every type in every test file, the project becomes harder to update.

A better approach is to keep small, feature-specific types near the code that uses them and move widely shared types into clearly named files.

This guide explains how to build that structure, why it matters, and how to use it in a realistic Playwright automation framework.

What Is Type Organization in a Playwright Project?

Type organization is the practice of arranging TypeScript interfaces, type aliases, and reusable models so that related Playwright code can share consistent definitions.

Consider a school library.

If every book is placed randomly, finding a particular subject becomes difficult. But when books are grouped into categories, anyone can find them more easily.

A Playwright project benefits from the same idea.

Instead of writing a user interface in five test files, define it once in a suitable shared location and import it wherever needed.

1. Why Should You Organize TypeScript Types?

Suppose an e-commerce automation framework has 100 tests.

Different tests use the following information:

  • Customer details for registration and login.

  • Product details for shopping cart tests.

  • Order details for checkout tests.

  • API response structures for service testing.

  • User roles for authorization checks.

If every test defines these structures separately, developers may unintentionally create different versions of the same model.

For example, one file might use email, while another expects emailAddress.

A shared type helps establish one consistent contract for related code.

Good type organization can improve readability, maintainability, code review, and refactoring. It can also help new team members understand how the project is structured.

2. Recommended Playwright TypeScript Folder Structure

There is no mandatory folder structure for every Playwright project. A practical structure for a medium-sized framework is:

playwright-project/

tests/

— Test scenarios

pages/

— Page Object classes

types/

— Shared data contracts

├── user.types.ts

├── product.types.ts

└── order.types.ts

fixtures/

— Reusable test setup

test-data/

— Sample test values

utils/

— Helper functions

api/

— API clients and helpers

playwright.config.ts

— Playwright configuration

tsconfig.json

— TypeScript configuration

Each folder has a specific purpose.

The tests/ folder contains testing scenarios. The pages/ folder contains reusable page interactions. The types/ folder holds shared type definitions, while test-data/ contains actual values used in tests.

Keeping types and test data separate is important because they serve different purposes.

For a broader framework explanation, explore the Playwright Framework guide.

3. Create a Shared Types Folder

Start by creating a folder named types.

Inside that folder, create a file named user.types.ts.

Define the structure of a user:

// types/user.types.ts


export interface User {

  id: number;

  name: string;

  email: string;

  role: 'admin' | 'customer';

}

The export keyword allows other files to import and reuse the interface.

Now create a test data file.

// test-data/users.ts


import type { User } from '../types/user.types';


export const testUser: User = {

  id: 101,

  name: 'Arun',

  email: 'arun@example.com',

  role: 'customer'

};

Notice the difference between the two files.

The type file describes what a valid user object should look like. The test data file supplies one actual user object.

You can now import testUser into tests or helpers.

import { testUser } from '../test-data/users';


console.log(testUser.email);

This makes the definition reusable without copying the same fields across different files.

4. Organize Types by Feature, Not Just by Data Type

As the project grows, you may need many interfaces.

Instead of keeping everything in one large types.ts file, group related models by business feature.

For example:

File

Types it contains

Used by

user.types.ts

User, UserRole

Login and profile tests

product.types.ts

Product, ProductCategory

Search and cart tests

order.types.ts

Order, OrderStatus

Checkout tests

payment.types.ts

PaymentMethod

Payment tests

api.types.ts

Shared API error models

API helpers

This approach helps developers locate the correct definition quickly.

However, you do not need a separate global file for every small type.

If a type is used by only one test or page class, keeping it near that code may be simpler.

A useful rule: Start with local types. Move a type into a shared folder when multiple parts of the project genuinely need it.

5. Use Shared Types in Page Object Model Classes

The Page Object Model, also called POM, organizes web page interactions into reusable classes.

A Page Object may contain locators for input fields, buttons, and other elements.

Instead of passing several unrelated values to a Page Object method, you can pass a typed object.

Create a login type:

// types/auth.types.ts


export interface LoginCredentials {

  email: string;

  password: string;

}

Next, create a login Page Object:

// pages/LoginPage.ts


import { Page } from '@playwright/test';


import type {

  LoginCredentials

} from '../types/auth.types';


export class LoginPage {

  constructor(private readonly page: Page) {}


  async goto(): Promise<void> {

    await this.page.goto('/login');

  }


  async login(

    credentials: LoginCredentials

  ): Promise<void> {

    await this.page.getByLabel('Email')

      .fill(credentials.email);


    await this.page.getByLabel('Password')

      .fill(credentials.password);


    await this.page.getByRole('button', {

      name: 'Sign in'

    }).click();

  }

}

Now create the test:

// tests/login.spec.ts


import { test, expect } from '@playwright/test';

import { LoginPage } from '../pages/LoginPage';


test('customer can log in', async ({ page }) => {

  const loginPage = new LoginPage(page);


  await loginPage.goto();


  await loginPage.login({

    email: 'customer@example.com',

    password: 'demoPassword123'

  });


  await expect(

    page.getByRole('heading', {

      name: 'Dashboard'

    })

  ).toBeVisible();

});

This is a reusable example for a matching test application, with baseURL configured.

The Page Object handles browser interactions. The interface describes the required login data. The test checks the result.

This separation makes it easier to change one part without unnecessarily changing another.

Read more in the Page Object Model in Playwright guide.

6. Keep Test Data Separate from Type Definitions

A common beginner mistake is to mix interfaces and actual test records in one large file.

Although TypeScript allows this, separating them can make growing frameworks easier to maintain.

For example, the product type might be:

// types/product.types.ts


export interface Product {

  id: string;

  name: string;

  price: number;

  available: boolean;

}

The test data can be stored separately:

// test-data/products.ts


import type { Product } from '../types/product.types';


export const laptop: Product = {

  id: 'P100',

  name: 'Student Laptop',

  price: 45000,

  available: true

};

Now you can reuse the product record across tests without changing its type definition.

This distinction becomes more important when test data changes often but the overall data structure remains stable.

Do not put actual customer passwords, production API tokens, or other secrets into test data files committed to source control.

7. Organize API Response Types Carefully

API testing requires additional attention because responses come from an external system.

Suppose a test sends a request to retrieve product information.

You may expect this response:

{

  "id": "P100",

  "name": "Student Laptop",

  "price": 45000

}

A TypeScript interface can describe that structure:

// types/product.types.ts


export interface ProductResponse {

  id: string;

  name: string;

  price: number;

}

However, an interface does not guarantee that the server actually returned these fields.

For a simple response check, validate the runtime values before relying on the object:

// tests/product-api.spec.ts


import { test, expect } from '@playwright/test';


test('product API returns expected fields',

  async ({ request }) => {

    const response = await request.get(

      '/api/products/P100'

    );


    expect(response.ok()).toBeTruthy();


    const body: unknown = await response.json();


    expect(body).toEqual(

      expect.objectContaining({

        id: expect.any(String),

        name: expect.any(String),

        price: expect.any(Number)

      })

    );

  }

);

This example assumes that the application provides a matching endpoint and that baseURL is configured.

It checks important field types at runtime. More complicated APIs may need complete schema validation, including nested objects and arrays.

The key point is simple: a TypeScript interface describes the expected response, but a runtime assertion or validator checks the actual response.

For related examples, read the Playwright API Testing tutorial.

8. Create Typed Custom Fixtures

Playwright fixtures provide reusable test setup and resources.

For example, if many tests need a LoginPage object, you can create a fixture rather than constructing it separately in every test.

// fixtures/test.ts


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

import { LoginPage } from '../pages/LoginPage';


type TestFixtures = {

  loginPage: LoginPage;

};


export const test = base.extend<TestFixtures>({

  loginPage: async ({ page }, use) => {

    const loginPage = new LoginPage(page);


    await use(loginPage);

  }

});


export { expect } from '@playwright/test';

A test can now import the custom fixture:

import { test, expect } from '../fixtures/test';


test('login page is available',

  async ({ loginPage, page }) => {

    await loginPage.goto();


    await expect(

      page.getByRole('button', {

        name: 'Sign in'

      })

    ).toBeVisible();

  }

);

The TestFixtures type tells TypeScript that the test receives a fixture named loginPage.

This allows TypeScript-aware editors to recognize it and provide appropriate suggestions.

Fixtures are useful, but beginners should not create complicated fixture systems before understanding ordinary tests and Page Objects.

For more examples, see the Playwright Fixtures guide. The official Playwright documentation also explains typed custom fixtures.

Playwright

9. Use import type for Type-Only Dependencies

TypeScript supports import type for imports that are needed only by the type system.

For example:

import type {

  Product

} from '../types/product.types';

This makes it clear that Product is being used as a type rather than as a JavaScript value.

Compare it with:

import { test } from '@playwright/test';

Here, test is a value used to define and run Playwright tests.

Using type-only imports can improve clarity and work well with strict TypeScript module settings.

Do not use import type for something that must exist at runtime, such as a class you are constructing with new.

10. Configure TypeScript for Better Type Checking

The tsconfig.json file defines how the TypeScript compiler checks your project.

A starting configuration for a Playwright test project might look like this:

{

  "compilerOptions": {

    "target": "ES2022",

    "module": "NodeNext",

    "moduleResolution": "NodeNext",

    "strict": true,

    "noEmit": true,

    "skipLibCheck": true

  },

  "include": [

    "tests/**/*.ts",

    "pages/**/*.ts",

    "types/**/*.ts",

    "fixtures/**/*.ts",

    "test-data/**/*.ts",

    "utils/**/*.ts",

    "api/**/*.ts",

    "playwright.config.ts"

  ]

}

This is an example configuration, not a universal requirement. Match module settings to your project's Node.js version, package settings, dependencies, and existing tooling.

The important options are:

Setting

Purpose

strict

Enables stronger TypeScript checks

noEmit

Checks types without outputting JavaScript files

include

Identifies files covered by this configuration

module

Defines the module system for compiler checking

moduleResolution

Controls how imports are resolved

skipLibCheck

Skips checking declaration files from dependencies

Run:

npx tsc --noEmit

Playwright can execute TypeScript tests without performing full compiler type checking, so this additional check is important.

Playwright

11. Should You Use One Global Types File?

For a very small project, one types.ts file may be enough.

For a larger project, a single file can become difficult to navigate when it contains unrelated customer, payment, product, and API definitions.

A better approach is to group models by feature and usage.

However, avoid creating too many small files simply to make the folder structure look advanced.

A good project structure should make real development work easier, not add unnecessary complexity.

12. When Should You Refactor Your Type Organization?

Consider reorganizing when the same interface appears in several files, developers frequently change multiple copies of the same model, or imports have become difficult to understand.

For example, if five tests define the same Product interface, move that definition into a shared file and update those tests to import it.

Run TypeScript checks and relevant tests after making the change.

Refactoring should preserve test behavior while improving code organization.

13. Common Mistakes in Type Organization

Common mistake

Better solution

Duplicating interfaces across test files

Share one suitable model

Putting every type in a massive file

Group types by related features

Exporting every local type

Export only what other modules require

Mixing credentials with public test data

Use secure test configuration

Creating complex generics for simple objects

Prefer readable interfaces

Using the same model for every unrelated API response

Define accurate response contracts

Moving all types into a global folder

Keep local types near their usage

Forgetting runtime validation

Check external data before trusting it

14. Practical Checklist for a Well-Organized Project

Playwright TypeScript project review

0/8 completed

Types shared across features have clear names and appropriate locations.

Feature-specific types remain near the code that uses them.

Test data is separated from type definitions where useful.

Page Objects use relevant Playwright types.

API responses are checked at runtime.

Type-only imports are used appropriately.

Strict TypeScript checking is enabled where practical.

Type checks and tests run after refactoring.

Reset checklist

Frequently Asked Questions

Where should TypeScript interfaces be stored in Playwright?

Store interfaces near the code that uses them. When an interface is shared by multiple tests, Page Objects, or helpers, place it in a clearly named shared module such as types/user.types.ts.

Is a types folder mandatory in Playwright?

No. Playwright does not require a dedicated types folder. It is an organizational choice that can help larger projects.

Should Page Object types be separate?

Reusable business-data types can be separate. Playwright's built-in Page and Locator types can be imported directly. Small types used by only one Page Object may remain in that file.

What is the difference between test data and types?

Types describe the expected structure of information. Test data contains the actual values used to exercise the application.

Can TypeScript validate API responses automatically?

No. TypeScript types are not runtime validators. API tests should validate actual server responses with assertions or schema-validation tools.

How do I know whether my project structure is good?

A good structure makes it easy to locate code, reuse common definitions, make changes safely, and understand which files are responsible for which features.

Conclusion

Organizing TypeScript types helps transform a collection of Playwright scripts into a project that is easier to understand and maintain.

Start with simple, local definitions. Share types when they are genuinely reused. Separate business models from test values and browser interactions, and use consistent naming conventions.

As your tests become more complex, combine these practices with Page Objects, fixtures, runtime validation, and separate TypeScript type checking.

Continue learning: Playwright Architecture Guide and Playwright Framework Development.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide