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.

More articles in this chapter