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

TypeScript › Object types: interface and type, optional, readonly

readonly and immutability

readonly forbids reassigning a field after creation, but only the compiler checks it, and at runtime the object is ordinary. The protection is shallow: a nested object stays mutable, so type-level deep immutability comes from as const or a copy per test, and at runtime Object.freeze blocks writes, also shallowly. Shared test data is made readonly and issued by a factory, so a mutating test does not break its neighbours.

TypeScript · Objects

A test expecting balance = 0 fails, but only when it runs after another. Who changed the shared object?

A test data file exports a single defaultUser object. One test "tops up" that user by increasing balance, and another expects zero and fails. Locally it is green, in CI it fails because tests are split between workers differently. This is a classic flaky test caused by shared mutable state, and readonly catches it at compile time. The lesson covers what exactly readonly protects and what it does not.

How it works and why. readonly is a marker checked only by the compiler: assigning to a readonly field is an error, but at runtime the object is ordinary. All code is written without protection, the protection exists only in the types. The check is also shallow: it concerns the field itself, not the contents of the object the field points to. Worth knowing too: in Playwright each worker is a separate process, so module state is not shared between workers, but it is shared by all tests the same worker runs, files included (a worker is reused until a test fails). That is why behaviour depends on which tests end up next to each other.

How many levels are protected

Readonly<T>top-level fields only, compilerreadonly string[]no push, sort, spliceas constall nesting levels, compilerObject.freezeruntime, but shallow as well
Figure 1. Four tools. Only as const covers all levels at compile time, and only freeze works at runtime.

Example: shared data and a flaky test.

// fixtures/users.ts
export const defaultUser = {
  email: 'a@test.io',
  balance: 0,
  limits: { daily: 1000 },
};

// test A
test('top up', async () => {
  defaultUser.balance += 100; // mutating a shared object
});

// test B in the same worker
test('new user has zero', async () => {
  expect(defaultUser.balance).toBe(0); // depends on order
});

Test B depends on whether A ran earlier in the same worker. The fix has two parts: forbid mutation with a type and give each test a fresh object from a factory.

export const DEFAULT_USER: Readonly<TestUser> = {
  email: 'a@test.io',
  balance: 0,
};

export const makeUser = (o: Partial<TestUser> = {}): TestUser => ({
  ...DEFAULT_USER,
  ...o,
});

// DEFAULT_USER.balance += 100; // compile error
const user = makeUser({ balance: 100 }); // a fresh object per test

Now mutating the default does not compile, and tests put changes into their own copy. But this works only because TestUser contains primitives. With a nested object (for example limits) Readonly does not help:

const config: Readonly<{ api: { timeout: number } }> = {
  api: { timeout: 5000 },
};
// config.api = {...}; // error
config.api.timeout = 1; // compiles!

const CONFIG = { api: { timeout: 5000 }, roles: ['admin', 'user'] } as const;
// CONFIG.api.timeout = 1; // error
// CONFIG.roles.push("x"); // error: readonly tuple

as const applies readonly at every level and turns arrays into readonly tuples. For existing types without a literal, people write their own DeepReadonly or copy the object with structuredClone. For arrays in helper parameters readonly T[] is useful:

function total(amounts: readonly number[]): number {
  // amounts.sort() does not compile: no mutation
  return amounts.reduce((s, a) => s + a, 0);
}

const sorted = amounts.toSorted((a, b) => a - b); // a copy, needs lib es2023

Limits and alternatives. First, readonly does not affect assignability: a value with a readonly field can be assigned to a variable with a mutable field and the compiler is silent. Second, nothing is blocked at runtime. Object.freeze gives real protection: in strict mode (ES modules and TS output use it) an attempt to change a frozen object throws TypeError. But freeze is shallow too and costs a bit of performance, so in tests it is used for shared constants, not everywhere.

interface Ro { readonly id: string }
interface Rw { id: string }

const ro: Ro = { id: 'x' };
const rw: Rw = ro; // compiles: readonly does not affect assignability
rw.id = 'y'; // and the mutation goes through

Common mistakes.

  • Treating Readonly<T> as deep: a nested object stays mutable and shared state leaks.
  • Protecting with a type only and not providing a fresh copy: another module using any will still change the data.
  • Thinking readonly works at runtime: after transpilation it is gone.
  • Passing a mutable array to a function that sorts it: sort changes the caller's array in place.

Check yourself

const cfg: Readonly<{ api: { timeout: number } }>. Why does cfg.api.timeout = 1 compile, and how do you close it?

Answer

Readonly protects only top-level fields, and api points to an ordinary object. You can close it with as const on the literal, a custom DeepReadonly, or by copying the object for each test.

A test that mutates the shared defaultUser passes steadily locally and occasionally breaks a neighbour in CI. Why only occasionally, and why not between all tests?

Answer

Playwright workers are separate processes with their own module state. A conflict arises only between tests of one worker, and the split between workers in CI differs from the local one. Hence the order dependence.

In an interview. Junior: readonly forbids overwriting a field after creation. It is a compiler check, there is nothing at runtime. Middle/Senior: The protection is shallow: for nested data I use as const or a copy per test, and Object.freeze for real runtime protection. Shared test data is readonly and handed out by a factory, so there is no order-dependent flaky test in a worker.

More articles in this chapter