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

TypeScript › Generics

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.

More articles in this chapter