QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript

Generics

Why generics: a typed API client

A generic (type parameter) links the input and output types of a call, so one client method returns the right type for any endpoint. That beats any or a copy per shape. But get<T> with T only in the result is a hidden as T: types are erased at runtime and nothing checks the data. It is safer to pass a schema and infer the type from it.

TypeScript · Generics

client.get("/accounts/42") returns any, the editor is silent, and a typo like balanse fails only in CI. How do you tie a type to a call?

An API client in a test framework is called hundreds of times, and each call returns its own shape: an account, a transfer, a page of a list. If the method returns any, mistakes in field names show up only at runtime. If you write a separate method for each shape, the code is duplicated. A generic (a type parameter) offers a third path: one method whose result type is tied to the call. The lesson covers how it works, where a generic promises more than it guarantees, and how to make the type really match the data.

How it works and why. The type parameter T is a variable that exists only at compile time. The function get<T>(path): Promise<T> says: "whatever you put in as T, I will return it". The substitution happens in two ways: explicitly (get<Account>(...)) or automatically, when the compiler infers T from the arguments. The key idea is that a generic links several places in a signature: input with output, a parameter with the result. Without it two poor choices remain: any (the link is lost) or a copy of the function per type. At runtime generics do not exist: types are erased like all others.

From any to an inferred type

json(): anytypos are invisible, there is no typeget<Account>(path)a type exists, but it is a promise (as T)get(path, AccountSchema)the type is derived from a verified schema
Figure 1. Each step adds a link between data and type. Only the last one checks data at runtime.

Example: from any to a schema. The start: the Playwright response res.json() returns any.

const res = await request.get('/api/accounts/42');
const acc = await res.json(); // any

console.log(acc.balanse.toFixed(2));
// compiles, TypeError at runtime: balanse does not exist

First step: wrap the call in a generic client method. The type Account is supplied at the call, and a typo in a field becomes a compile error.

class ApiClient {
  constructor(private readonly request: APIRequestContext) {}

1  async get<T>(path: string): Promise<T> {
    const res = await this.request.get(path);
    expect(res.ok()).toBeTruthy();
2    return (await res.json()) as T;
  }
}

3const acc = await api.get<Account>('/api/accounts/42');
acc.balance.toFixed(2); // number, autocompletion works
  1. get<T>: the type parameter T appears only in the result type, so it links nothing to the input. It is a hidden as, which is why a schema replaces it below.
  2. as T is an assertion, not a check: the compiler trusts it, the data is not verified.
  3. The call sets the type: get<Account> makes acc typed.

But honestly: as T promises what it does not know. If the server returns balance as a string, the type lies and the bug is back. So the second step moves the check into the client: the method takes a schema and the type is inferred from it.

import { z } from 'zod';

const AccountSchema = z.object({
  id: z.string(),
  balance: z.number(),
});

class ApiClient {
  constructor(private readonly request: APIRequestContext) {}

  async get<S extends z.ZodType>(path: string, schema: S): Promise<z.infer<S>> {
    const res = await this.request.get(path);
    expect(res.ok()).toBeTruthy();
    return schema.parse(await res.json());
  }
}

const acc = await api.get('/api/accounts/42', AccountSchema);
// acc: { id: string; balance: number }, no angle brackets

A manual type or a schema

Wrong

get<Account>(path)

The type is stated by hand and promised through as T. A mismatch with the API breaks nothing until a test fails.

Right

get(path, AccountSchema)

The schema validates the response and is the source of the type. A mismatch fails at once with a description of the field.

Figure 2. The type should come from a check, not be a separate promise.

Limits and alternatives. The best generics are those the compiler infers itself: no angle brackets at the call site and no way to state the wrong type. Explicit substitution is justified when there is nothing to infer from. A generic is useful where it links several places: a paginated response Page<T>, a retry<T> wrapper, a data factory. When a type parameter appears only once it links nothing: in a parameter it equals unknown, and in the result type it is an unchecked as, like get<T> above. In test code complex generics are better hidden in the framework layer: a test should read quickly.

interface Page<T> { items: T[]; total: number }

async function retry<T>(fn: () => Promise<T>, times = 3): Promise<T> {
  let last: unknown;
  for (let i = 0; i < times; i++) {
    try {
      return await fn();
    } catch (e) {
      last = e;
    }
  }
  throw last;
}

const page = await retry(() => api.get('/api/accounts', PageSchema));

Common mistakes.

  • as T inside the client with no check: the type looks strict, yet there are no guarantees.
  • Stating <Account> where the type can be inferred from an argument: noise and a risk of getting it wrong.
  • A type parameter that appears once: it is unknown in fancier clothes.
  • Overly clever generics in the tests themselves: they are harder than the code they check.

Check yourself

A client get<Account> with as T compiles, yet the test fails on acc.balance.toFixed with is not a function. Where is the bug and how do you remove it?

Answer

The server returned balance as a string and as T merely asserts the type. The type and the data drifted apart. The fix: pass a schema to the method and infer the type from it, so a mismatch fails on input.

Why is function log<T>(x: T): void no better than function log(x: unknown): void?

Answer

The parameter T appears only once and links nothing: the result does not depend on it. A generic makes sense when it links input with output or several parameters.

In an interview. Junior: A generic is a type parameter: one method get<T> returns the right type for any endpoint, instead of any or duplicated code. Middle/Senior: An explicit <T> with as T only promises a type. So the client takes a schema and the type is inferred through z.infer: the check and the type cannot drift apart. A type parameter that appears once is usually superfluous.

Constraints, keyof and defaults

An extends constraint sets the minimum shape of a type parameter, and keyof gives a union of field names. Combining K extends keyof T and T[K] gives an exact result type, and a typo in a field name does not compile. Return T, not the constraint, so fields are not lost. If a type parameter appears only once, no generic is needed.

TypeScript · Generics

pluck(rows, "amout") returns an array of undefined and the sum becomes NaN. How do you stop such a typo from compiling?

Almost every automation engineer writes a helper that pulls a column from an array of objects: transaction amounts, account ids, statuses. Typed as key: string it accepts any string, and a typo in a field name gives an array of undefined and then NaN in a check. The lesson shows three tools that make such a helper safe: the extends constraint, keyof and a default for a type parameter.

How it works and why. A plain T promises nothing: inside the function all that is known about it is that it exists, so accessing fields is impossible. The constraint T extends HasId says the substituted type must contain at least those fields. Inside you can read item.id, while from outside T stays exact: it returns T itself, not the narrower HasId. keyof T gives a union of field names: for Transaction that is 'id' | 'amount' | 'currency'. The parameter K extends keyof T allows only such strings, and T[K] (indexed access) is the type of exactly that field. The compiler takes the literal 'amount' from the call, substitutes it as K and computes number.

How T[K] is inferred

Argument "amount"a literal, not just stringK = "amount"K extends keyof TransactionT[K] = numberthe type of the amount field in TransactionResult number[]a typo fails the K check
Figure 1. Four steps of inference. A typo is stopped at the second.

Example: from any to a constrained generic. The helper as it can be seen in a test repository:

function pluck(rows: any[], key: string): any[] {
  return rows.map((r) => r[key]);
}

const amounts = pluck(transactions, 'amout'); // any[], the typo is invisible
const total = amounts.reduce((s, a) => s + a, 0); // NaN

Nothing stops the typo 'amout': r['amout'] gives undefined, reduce adds undefined to a number and returns NaN. The test fails with a puzzling comparison of NaN, and the cause has to be hunted down. With the constraint:

1function pluck<T, K extends keyof T>(rows: readonly T[], key: K): T[K][] {
  return rows.map((r) => r[key]);
}

const amounts = pluck(transactions, 'amount'); // number[]
2// pluck(transactions, 'amout'); // error: no such key
  1. K extends keyof T: the key can only be an existing field, and the result T[K][] matches the field exactly.
  2. A typo is now a compile error, not NaN at runtime.

Another win of a constraint is keeping the exact type. Compare two variants of lookup by id:

A type parameter or a narrower type

Wrong

items: HasId[]: HasId

The result has type HasId: all other fields (balance) are lost and an as becomes necessary.

Right

T extends HasId: T

The result stays Account. The constraint only allows reading id inside.

Figure 2. A constrained generic returns the original type, not its "constraint".
interface HasId { id: string }

function byIdLoose(items: readonly HasId[], id: string): HasId | undefined {
  return items.find((i) => i.id === id);
}

function byId<T extends HasId>(items: readonly T[], id: string): T | undefined {
  return items.find((i) => i.id === id);
}

const a = byIdLoose(accounts, '42')?.balance; // error: balance is not in HasId
const b = byId(accounts, '42')?.balance; // number | undefined

A type parameter can have a default: Page<T, Meta = { total: number }> lets you write Page<Account> where Meta is standard and state it where it differs. In addition, since TypeScript 5.0, there are const type parameters: they keep literals and tuples without as const at the call site.

interface Page<T, Meta = { total: number }> {
  items: T[];
  meta: Meta;
}

type AccountsPage = Page<Account>;
type CursorPage = Page<Account, { next: string | null }>;

function first<const T extends readonly unknown[]>(xs: T): T[0] {
  return xs[0];
}
const f = first(['UAH', 'USD']); // 'UAH'

Limits and alternatives. keyof works with static keys: for dictionaries with arbitrary keys (Record<string, ...>) it gives string and the whole check disappears. Nested paths like 'user.address.city' need template literal types or a library, and complexity grows fast. So in tests people usually keep one level. If the helper is needed once, it is simpler to write rows.map(r => r.amount): the types are inferred on their own.

Common mistakes.

  • The key as string instead of K extends keyof T: a typo turns into undefined.
  • Returning the constraint (HasId) instead of T: fields are lost and an as appears.
  • Stating parameters by hand when they can be inferred from the arguments.
  • Complex generics in tests: the checking code becomes harder than the code under test.

Check yourself

In pluck<T, K extends keyof T>(rows, key: K): T[K][] the call pluck(rows, 'amount') returns number[]. How does the compiler know?

Answer

The literal 'amount' becomes the value of K (since K is constrained by keyof T), and T[K] is the type of the amount field in T, i.e. number.

A function finds an item by id: (items: HasId[], id): HasId | undefined. Why is the account balance field unavailable after it, and how do you fix it?

Answer

The result has type HasId, so other fields are invisible. The fix: <T extends HasId>(items: readonly T[], id): T | undefined, then the type comes back exact.

In an interview. Junior: extends constrains a type parameter, for example T extends HasId, and keyof gives the field names of an object. Middle/Senior: Combining K extends keyof T and T[K] gives helpers where a typo in a field name does not compile and the result type is exact. The constraint allows reading fields inside, but I return T, not the constraint. If a type parameter appears once, no generic is needed.

Generics in Playwright: fixtures

The generics of test.extend describe fixture types: the first parameter is for test fixtures, the second for worker fixtures. So a Page Object or API client is typed in every test without !. Options are declared as [value, { option: true }] and their values come from the config. A test must import test from your own file, not from @playwright/test, otherwise the fixture types do not reach it.

TypeScript · Generics

A helper in a test with let api: ApiClient | undefined demands ! everywhere. How do you make api ready and typed in every test?

A typical framework keeps objects such as LoginPage or ApiClient in variables created in beforeEach. Such a variable has the type "an object or undefined", so every test is forced to use !. Playwright fixtures remove the problem: a component is created for a test and its type is known. Generics here are the way to tell Playwright which fixtures were added. The lesson covers how it is arranged and where type errors show up most sharply.

How it works and why. The test.extend method takes generic parameters: the first (TestFixtures) describes test-scoped fixtures, the second (WorkerFixtures) worker-scoped ones. The object passed to extend is checked by the compiler against those types: every fixture has to be implemented, and dependencies in the destructuring ({ page }) are typed from the fixtures that already exist, built-in and added earlier. The use parameter accepts a value of the type declared in the description. After that every test gets typed fixtures from its destructuring. The design is needed because fixture names are string keys: without a type description TypeScript would have no way to know that api is an ApiClient. A fixture is created only when a test asks for it.

Where fixture types come from

type TestFixtures = {...}a description of what a fixture providesbase.extend<Test, Worker>the generic ties the description to the implementationasync ({ page }, use)dependencies are typed automaticallytest("...", ({ api }) =>api: ApiClient in every test
Figure 1. One description of types flows into the implementation and every test.

Example: from a variable to a fixture. Before:

let api: ApiClient | undefined;

test.beforeEach(({ request }) => {
  api = new ApiClient(request);
});

test('user sees balance', async () => {
  const acc = await api!.get('/api/accounts/42', AccountSchema);
  expect(acc.balance).toBeGreaterThan(0);
});

Here ! removes the check: if the hook did not run, the test fails on undefined and not with a meaningful error. Moreover a module-level variable is shared by the tests of one worker. With fixtures:

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

type TestFixtures = { loginPage: LoginPage; api: ApiClient };
type WorkerFixtures = { account: Account };

1export const test = base.extend<TestFixtures, WorkerFixtures>({
  loginPage: async ({ page }, use) => {
    await use(new LoginPage(page));
  },
2  api: async ({ request }, use) => {
    await use(new ApiClient(request));
  },
  account: [
    async ({}, use) => {
      const acc = await createAccount();
      await use(acc);
      await deleteAccount(acc.id);
    },
3    { scope: 'worker' },
  ],
});

4test('user sees balance', async ({ api, account }) => {
  const fresh = await api.get('/api/accounts/' + account.id, AccountSchema);
  expect(fresh.balance).toBeGreaterThanOrEqual(0);
});
  1. Descriptions of test and worker fixtures are separate: the two generic parameters of extend.
  2. Dependencies like { request } are typed automatically, and use accepts an ApiClient.
  3. A worker fixture is given as a pair [function, { scope: 'worker' }]: the account is created once per worker.
  4. The test gets api and account with types and no !.

A test or a worker fixture

Test

extend<TestFixtures>

Created for each test, isolated. For page, clients, Page Objects.

Worker

extend<{}, WorkerFixtures>

Created once per worker and shared by its tests. For expensive resources: an account, a database.

Figure 2. Both options are legitimate: the difference is how long the object lives.

The third kind of fixtures is options. A fixture is declared as [value, { option: true }], its value is set in the config, and the config type is passed as a generic to defineConfig. That way, for example, one set of tests runs for different currencies or markets:

// fixtures.ts
export type TestOptions = { currency: 'UAH' | 'USD' };

export const test = base.extend<TestOptions>({
  currency: ['UAH', { option: true }],
});

// playwright.config.ts
export default defineConfig<TestOptions>({
  projects: [
    { name: 'uah', use: { currency: 'UAH' } },
    { name: 'usd', use: { currency: 'USD' } },
  ],
});

When fixtures multiply they are split by topic and combined through mergeTests, which also preserves the types:

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

export const test = mergeTests(dbTest, apiTest);
// a test sees the fixtures of both

Limits and alternatives. Fixture types check only the consistency of the code, not what a fixture really creates. A worker fixture cannot depend on test-scoped fixtures (page, request): it lives longer, and the compiler reflects that. Playwright already has expect.poll for custom expectations, so writing your own generic pollUntil<T> is worth it only when that is not enough. The alternative to fixtures, classes with a constructor and beforeEach, works but brings back the undefined problem.

Common mistakes.

  • Describing a worker fixture in the first generic parameter: in the docs they go in the second.
  • Keeping a Page Object in a module variable with !: the type lies and the state is shared by tests.
  • A worker fixture depending on page or request: they exist only for the duration of a test.
  • Importing test from @playwright/test instead of your own: fixture types will not reach the test.

Check yourself

A test imports test from @playwright/test, while the api fixture is declared in fixtures.ts. What will the compiler show and why?

Answer

An error: the property api does not exist among the fixtures. Types are added only to the test returned by base.extend<...>, so tests must import it from fixtures.ts.

Why does base.extend have two generic parameters instead of one?

Answer

Test and worker fixtures have different lifetimes and different allowed dependencies. Two parameters let the compiler tell them apart: a worker one cannot depend on test ones.

In an interview. Junior: Fixtures are typed through test.extend<Fixtures>(): then a Page Object and an API client have a type in every test with no !. Middle/Senior: The first generic describes test fixtures, the second worker ones, and options are set through { option: true } and defineConfig<Options>. I import test only from my own file, combine sets through mergeTests and keep expensive resources in worker fixtures.