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

TypeScript

Utility types

Partial, Required, Readonly, Pick, Omit

Partial makes all fields optional, Required removes that, Readonly adds readonly, Pick keeps the chosen keys and Omit removes them; all are mapped types. Traps: Omit does not check its key, so a typo removes nothing, and Partial without exactOptionalPropertyTypes allows an explicit undefined, which a spread carries into the result. Readonly and Partial are shallow, and Readonly has no effect at runtime.

TypeScript · Utility types

A data factory takes Partial, a test passes undefined from config, and the request goes out without a currency. Why are types silent?

A test data factory exists in almost every framework: the base object is valid, and a test overrides only what matters for the scenario. The natural parameter type for it is Partial<TransferRequest>. Everything compiles, tests are green, then the request reaches the server without the currency field and the investigation looks like a backend bug. This lesson is about five utilities that build one type from another, how they are made, and where each quietly allows too much.

How it works and why. The utilities are ordinary generic types from the TypeScript standard library, not special magic. All five are built on mapped types (they walk over the keys of keyof T) and exist so a model is not copied. Here is their simplified shape:

type Partial<T> = { [P in keyof T]?: T[P] };
type Required<T> = { [P in keyof T]-?: T[P] };
type Readonly<T> = { readonly [P in keyof T]: T[P] };
type Pick<T, K extends keyof T> = { [P in K]: T[P] };
type Omit<T, K extends keyof any> =
  Pick<T, Exclude<keyof T, K>>;

Partial adds ? to every key, Required removes it (-?), Readonly adds readonly. Pick keeps the listed keys, Omit removes them. Note the difference in the constraint: Pick requires K extends keyof T, so a wrong key does not compile, while Omit has keyof any, that is, any key. This is deliberate: Omit has to work even when a key is missing from the type (for example from one member of a union), but the price is no hint about a typo.

One model, several derived types

Transfer, Accountone model: the source of truthPartial<Transfer>overrides in a data factoryOmit<Account, 'id' | 'createdAt'>the create request bodyPick<Account, 'id' | 'iban'>a short view for a list
Figure 1. Change a field in the model and every derived type follows. Separately maintained copies do not.

Example: a factory that quietly lets undefined through. A base model, a factory and a test that takes the currency from an environment variable:

type Currency = 'UAH' | 'USD';

interface TransferRequest {
  fromAccount: string;
  toAccount: string;
  amount: number;
  currency: Currency;
  description: string;
}

const base: TransferRequest = {
  fromAccount: 'UA213223130000026007233566001',
  toAccount: 'UA903052992990004149123456789',
  amount: 10_000,
  currency: 'UAH',
  description: 'autotest',
};

function buildTransfer(
  overrides: Partial<TransferRequest> = {},
): TransferRequest {
  return { ...base, ...overrides };
}
const fromEnv = process.env.TEST_CURRENCY as Currency | undefined;

const transfer = buildTransfer({ currency: fromEnv });
// the type says Currency, the runtime value is undefined
await request.post('/api/transfers', { data: transfer });

Why this passes. In Partial every field looks like currency?: Currency, and without the exactOptionalPropertyTypes option an optional field allows an explicit undefined value. The spread { ...base, ...overrides } takes every own key of the second object, including a key whose value is undefined, and overwrites the base value with it. The types still consider the result a TransferRequest, because the compiler computes a spread of optional properties as "either the override value or the base one". Then JSON.stringify simply drops undefined and the server gets a request without a currency.

There are two fixes, best combined. First: remove the possibility from the type with exactOptionalPropertyTypes; then { currency: undefined } does not compile and the value from process.env has to be narrowed explicitly.

{
  "compilerOptions": {
    "strict": true,
    "exactOptionalPropertyTypes": true
  }
}

Second: in the factory itself, drop keys with undefined before merging, to protect against values the types cannot see (for example ones that came through any or from JSON).

const defined = <T extends object>(o: T): T =>
  Object.fromEntries(
    Object.entries(o).filter(([, v]) => v !== undefined),
  ) as T;

function buildTransfer(
  overrides: Partial<TransferRequest> = {},
): TransferRequest {
  return { ...base, ...defined(overrides) };
}

Partial in a factory

Wrong

{ ...base, ...overrides }

An explicit undefined in the overrides overwrites the base value. The type stays TransferRequest, the request has a hole.

Right

exactOptionalPropertyTypes and defined()

The compiler forbids an explicit undefined, and the factory drops such keys for data the types cannot see.

Figure 2. Partial lets a key be omitted, but without extra settings and a check it cannot tell "omitted" from "undefined".

Pick, Omit and a create body. The server generates id and createdAt itself, so the create body is the model without them, and a short list view is part of it:

interface Account {
  id: string;
  iban: string;
  currency: Currency;
  createdAt: string;
}

type CreateAccountBody = Omit<Account, 'id' | 'createdAt'>;
type AccountSummary = Pick<Account, 'id' | 'iban'>;

type A = Omit<Account, 'idd'>; // compiles, nothing is removed
type B = Pick<Account, 'idd'>; // error: no such key

If a new field appears in Account, CreateAccountBody gets it automatically. The second line with Omit shows the price of flexibility: the typo 'idd' removes nothing and the type quietly stays whole. For critical places people write a stricter version of their own (type StrictOmit<T, K extends keyof T> = Omit<T, K>) or simply check the result with a type test.

Limits and alternatives.

  • Partial, Required and Readonly are shallow: a nested object payer: { name, iban } stays whole. To override only payer.name you need your own DeepPartial or to override the whole nested object.
  • Readonly<T> acts only in the compiler. At runtime the object can change unless it is frozen with Object.freeze.
  • Omit does not distribute over a union: Omit<A | B, 'x'> keeps only the common keys and loses the discriminant. A union needs a distributive variant of your own.
  • For data with many variants, separate builder methods (withAmount, inCurrency) are often better than Partial: they read like a scenario.

Common mistakes.

  • Allowing an explicit undefined in Partial and merging with a spread: the field disappears from the request with no error.
  • Treating Omit as a key check: a typo is not caught.
  • Expecting Readonly to protect at runtime: it is only a hint to the compiler.
  • Copying a model by hand into several interfaces instead of deriving: half a year later the fields have drifted apart.

Check yourself

buildTransfer({ amount: undefined }) compiles and the server answers 400. What exactly happened, and what changes in the type and in the factory?

Answer

Without exactOptionalPropertyTypes Partial allows an explicit undefined, the spread overwrites the base amount with it, and the field vanishes from the JSON. Turn on exactOptionalPropertyTypes in tsconfig and drop undefined keys in the factory before merging.

Why does Pick<Account, 'idd'> give an error while Omit<Account, 'idd'> does not?

Answer

Pick limits keys to keyof T, Omit accepts any key at all (keyof any). So an Omit with a typo removes nothing and does not complain.

In an interview. Junior: Partial makes all fields optional, Pick keeps chosen ones, Omit removes them. I use Partial in test data factories so a test overrides only the needed fields. Middle/Senior: They are all mapped types, and they have traps: Omit does not check the key, Partial allows an explicit undefined that a spread carries into the result, and Readonly is shallow and absent at runtime. So I turn on exactOptionalPropertyTypes and drop undefined keys in the factory.

Record, Exclude, Extract, NonNullable

Record over a union of keys requires every key, Exclude removes union members, Extract keeps them and NonNullable drops null and undefined. Exclude and Extract are distributive conditional types that test each union member separately. So a map keyed by the full union does not build without a new currency, while one keyed by a plain string requires nothing and lies about missing keys.

TypeScript · Utility types

JPY was added to Currency, and the decimals map said nothing. How do we make the compiler demand every key?

A test utility converts an amount to the minor units of a currency. The map { UAH: 2, USD: 2, EUR: 2 } was written long ago, and Currency now also has JPY. The function returns NaN for yen, the test fails, and the compiler said nothing. This lesson is about four utilities that turn unions and object types into "complete tables" and filters: Record, Exclude, Extract, NonNullable.

How it works and why. Record<K, V> is a mapped type over the keys K. If K is a union of literals, each member becomes a required key, so the map has to cover every variant. Exclude and Extract are conditional types that distribute over a union: the condition is checked for each member separately and the result is gathered back into a union. Since TypeScript 4.8, NonNullable is the intersection T & {}, which drops null and undefined. Simplified:

type Record<K extends keyof any, T> = { [P in K]: T };
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;
type NonNullable<T> = T & {};

What each utility keeps

'PENDING' | 'COMPLETED' | 'FAILED'the source unionExclude<…, 'PENDING'>leaves 'COMPLETED' | 'FAILED'Extract<…, 'FAILED'>leaves only 'FAILED'NonNullable<string | null>leaves string
Figure 1. Exclude and Extract handle each union member separately, NonNullable removes only null and undefined.

Example: a map that does not notice a new currency. Typical code where the map was described as Record<string, number> because it is simpler:

type Currency = 'UAH' | 'USD' | 'EUR';

const minorUnits: Record<string, number> = {
  UAH: 2,
  USD: 2,
  EUR: 2,
};

function toMinor(amount: number, c: Currency): number {
  return Math.round(amount * 10 ** minorUnits[c]);
}

The key string accepts any set of keys, so neither adding JPY to Currency nor leaving it out of the map gives an error. The access minorUnits[c] returns undefined, 10 ** undefined is NaN, and Math.round also gives NaN. The types did not help because they promised "a number is always there".

The fix is to tie the map keys to the union: Record<Currency, number>. The satisfies operator checks completeness without changing the inferred type, and together with as const the values stay exact literals (2, 0) instead of widening to number:

type Currency = 'UAH' | 'USD' | 'EUR' | 'JPY';

const minorUnits = {
  UAH: 2,
  USD: 2,
  EUR: 2,
  JPY: 0,
} as const satisfies Record<Currency, number>;

function toMinor(amount: number, c: Currency): number {
  return Math.round(amount * 10 ** minorUnits[c]);
}

Now deleting JPY from the map or adding a new currency without an entry is impossible: the compiler complains about the missing key. There is a domain benefit too: JPY has 0 decimal places while most currencies have 2 (ISO 4217 also has currencies with 3, such as KWD), so "all are 2" was a wrong assumption, not just a convenience.

A currency map

Wrong

Record<string, number>

Any key passes. A new currency without an entry gives undefined and then NaN in calculations.

Right

as const satisfies Record<Currency, number>

The compiler demands an entry for every currency, and the values stay exact literals.

Figure 2. A complete map turns "forgot to add" into a compile error.

Exclude, Extract and filtering a union. A helper that waits for a final status needs a type without PENDING:

type TxStatus = 'PENDING' | 'COMPLETED' | 'FAILED' | 'REVERSED';
type FinalStatus = Exclude<TxStatus, 'PENDING'>;

async function waitForStatus(
  id: string,
  expected: FinalStatus,
): Promise<void> {
  await expect
    .poll(() => api.getTransfer(id).then((t) => t.status))
    .toBe(expected);
}

await waitForStatus(id, 'COMPLETED'); // ok
await waitForStatus(id, 'PENDING'); // compile error

A pointless test that waits for a "final" PENDING does not compile. Extract works with object types by assignability: Extract<AppEvent, { amount: number }> keeps the members assignable to that type, and picking by the discriminant is more reliable.

type AppEvent =
  | { type: 'deposit'; amount: number }
  | { type: 'withdrawal'; amount: number }
  | { type: 'blocked'; reason: string };

type MoneyEvent = Extract<AppEvent, { amount: number }>;
type DepositEvent = Extract<AppEvent, { type: 'deposit' }>;
type NonBlocked = Exclude<AppEvent, { type: 'blocked' }>;

One more filter: NonNullable<string | null | undefined> is string. It describes a value after a check, for example the result of filter with a type guard.

Limits and alternatives.

  • Record<string, V> lies about missing keys: access gives V while at runtime it may be undefined. The noUncheckedIndexedAccess option or the type Partial<Record<string, V>> helps. For dynamic keys a Map is sometimes better.
  • Exclude and Extract change only the type, not values. If a union is written by hand apart from the API, it can lag behind the server: types do not know the backend added a status.
  • To walk the keys of a Record you need Object.keys, which returns string[], not keyof T: an explicit cast or an as const array is needed.

Common mistakes.

  • Record<string, V> where the keys are known: the map does not demand completeness.
  • An annotation : Record<Currency, number> instead of as const satisfies when exact literal values are needed: they widen to number.
  • Picking union members with Extract by an arbitrary shape when a discriminant exists: variants that are assignable by accident get into the selection.
  • Thinking NonNullable also removes empty strings or zero: only null and undefined.

Check yourself

The map const m: Record<string, number> = { UAH: 2, USD: 2 } compiles, and m['EUR'] returns undefined. What should change so that EUR without an entry does not build?

Answer

Tie the keys to the union: Record<Currency, number> (better via as const satisfies to keep the exact values). Then a missing key is a compile error.

What type does Exclude<'A' | 'B' | 'C', 'B'> give, and why does it work for each member separately?

Answer

It is 'A' | 'C'. Exclude<T, U> is T extends U ? never : T, and a conditional type distributes over a union: each member is checked, and those that fit U become never and vanish from the result.

In an interview. Junior: Record with a union of keys requires every key, so a map covers all variants, for example all currencies. Exclude and Extract filter a union. Middle/Senior: Exclude and Extract are distributive conditional types, and Record<string, V> demands nothing and lies about missing keys, so for known keys I use satisfies Record<Union, V>, and for dynamic ones I turn on noUncheckedIndexedAccess.

ReturnType, Parameters, Awaited

ReturnType gives the type of the value a function returns, Parameters a tuple of its argument types, and Awaited recursively unwraps a Promise. For an async function the result is Awaited<ReturnType<typeof fn>>, because ReturnType gives the Promise itself. This derives the result types of factories and fixtures from the implementation without a second source of truth. API contracts come from OpenAPI, not from the implementation, since an inferred type repeats its bugs.

TypeScript · Utility types

The result interface of a fixture was written by hand, the function changed, and the test still compiles. Where does the type come from?

A helper seedAccount creates a user through the API and returns an object. Next to it someone wrote a manual interface SeededAccount to pass that object into other functions. A month later the helper got a token field that the interface lacks, and the compiler does not notice the stale type. This lesson is about three utilities that derive types straight from functions: ReturnType, Parameters, Awaited.

How it works and why. ReturnType<typeof fn> takes the type of the value the function returns. Parameters<typeof fn> gives a tuple of argument types, keeping names and optionality. Both are built on infer in a conditional type, that is "substitute whatever is there". Awaited<T> (since TypeScript 4.5) recursively unwraps a Promise and any thenable. It is needed because an async function always returns a Promise, and ReturnType gives exactly that, not the result.

The result type of an async function

typeof seedAccountan async function with a bodyReturnType<…>Promise<{ id, role, balance, token }>Awaited<…>{ id, role, balance, token }: the result type
Figure 1. ReturnType returns a Promise, so without Awaited the result type cannot be obtained.

The difference between a value and a type matters here. The function seedAccount is a value, and in a type position it is taken with the typeof operator. The form ReturnType<seedAccount> without typeof does not compile.

Example: two sources of truth. A manual interface next to the function that produces it:

interface SeededAccount {
  id: string;
  role: string;
  balance: number;
}

async function expectBalance(acc: SeededAccount, amount: number) {
  const res = await api.get('/accounts/' + acc.id);
  expect((await res.json()).balance).toBe(amount);
}

The role field in the interface is string while the function returns the narrower 'admin' | 'viewer'. The token field is absent from the interface altogether, so functions that need it must repeat as or carry the variable separately. Structural typing lets an object with an extra field be passed, so there is no error. The types drifted apart quietly.

The fix is to have no second source: derive the type from the implementation.

async function seedAccount(
  role: 'admin' | 'viewer',
  balance = 0,
) {
  const res = await api.post('/test/accounts', {
    data: { role, balance },
  });
  const { id, token } = await res.json();
  return { id: id as string, role, balance, token: token as string };
}

type SeededAccount = Awaited<ReturnType<typeof seedAccount>>;
type SeedArgs = Parameters<typeof seedAccount>;
type SeededAccount = Awaited<ReturnType<typeof seedAccount>>;

async function expectBalance(acc: SeededAccount, amount: number) {
  const res = await api.get('/accounts/' + acc.id);
  expect((await res.json()).balance).toBe(amount);
}

Now a field added to the helper, token, is immediately visible in SeededAccount, and the narrowing of role is kept. This is especially handy for fixture results, where a separate interface would only duplicate code.

A wrapper that keeps the signature. Parameters and Awaited<ReturnType<F>> make it possible to write a wrapper that loses neither the arguments nor the result type, for example wrapping a call in test.step:

function withStep<F extends (...args: any[]) => Promise<unknown>>(
  title: string,
  fn: F,
) {
  return async (
    ...args: Parameters<F>
  ): Promise<Awaited<ReturnType<F>>> => {
    return test.step(title, async (): Promise<Awaited<ReturnType<F>>> => {
      return (await fn(...args)) as Awaited<ReturnType<F>>;
    });
  };
}

const seed = withStep('Seed account', seedAccount);
const acc = await seed('admin', 500);

The constraint (...args: any[]) is a deliberate and accepted trick here: any function fits it, while the real argument and result types still come from F. The result of seed has the same parameters ('admin' | 'viewer', number?) and the same result type as seedAccount.

Where the type comes from

Wrong

A separate interface

A second description next to the function. A field was added to the code and is absent from the interface, and nobody noticed.

Right

Awaited<ReturnType<typeof fn>>

The type always matches what the function actually returns.

Figure 2. A derived type cannot drift from the implementation because it is derived from the implementation.

Limits and alternatives.

  • A derived type follows the implementation, including its bugs. If the source of truth is an external contract (OpenAPI), types are generated from it, and then the implementation must match the contract, not the other way round.
  • For a function with overloads, ReturnType and Parameters use the last signature, not all of them. For a generic function, type parameters are replaced by their constraints.
  • For classes there are ConstructorParameters and InstanceType, and for this in a method ThisParameterType.
  • When many files use a function's type, it is handier to name it once in a module (export type SeededAccount = …) and import it.

Common mistakes.

  • ReturnType<typeof asyncFn> without Awaited: the result is a Promise, and its fields are not reachable.
  • Forgetting typeof before the function name.
  • Duplicating a function result in a separate interface that later lags behind.
  • Deriving an API contract type from a test helper implementation: the type adapts to the bug and never shows a mismatch.

Check yourself

Why does ReturnType<typeof seedAccount> for an async function not give the needed fields, and what should be added?

Answer

Because an async function returns a Promise, and ReturnType returns it with the wrapper. Awaited unwraps the promise: Awaited<ReturnType<typeof seedAccount>>.

What happens to the type Awaited<ReturnType<typeof fn>> if the return type of fn changes?

Answer

The type changes with the function because it is derived from it. Every place that uses it either picks up the change automatically or gives a compile error if it no longer fits.

In an interview. Junior: ReturnType gives the type a function returns, Parameters the type of its arguments, and Awaited unwraps a Promise. For an async function the result is Awaited<ReturnType<typeof fn>>. Middle/Senior: This is how I derive result types of factories and fixtures and write wrappers that keep the signature, with no second source of truth. But I take API contracts from OpenAPI, not from an implementation: a derived type repeats its bugs.