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

TypeScript

Object types: interface and type, optional, readonly

interface or type

For a plain object shape interface and type are almost interchangeable, and the choice matters in four places. Type also names unions and tuples and implicitly has an index signature, while interface allows declaration merging (how fields are added to Window) and extends, which rejects conflicting fields, whereas an & intersection quietly gives never. In practice: interface for models and classes, type for the rest.

TypeScript · Objects

You add a field to Window with type and the compiler says "Duplicate identifier". Why does interface allow it?

Tests often add their own globals to the page (an app-ready flag), and API models are described sometimes with interface, sometimes with type. For a plain object shape there is almost no difference, so people choose at random. Still, there are four places where the choice changes what the compiler does. The lesson covers them and gives a rule that does not need rechecking every time.

How it works and why. TypeScript types structurally: two types are compatible when their shapes match, not their names. That is why interface and type are interchangeable for an object. But they are the same only for a plain object shape. type names any type: a union, a tuple, a primitive, a function, a mapped or conditional type. interface describes only the shape of an object (and of a call or a constructor), but its declaration is open: two interfaces with the same name merge into one (declaration merging). That is how libraries let you extend their types, and how you add fields to Window or process.env. type is closed: a second declaration with the same name is an error.

// global.d.ts: add a field to the built-in Window
declare global {
  interface Window {
    appReady?: boolean;
  }
}
export {};

// in a test
await page.waitForFunction(() => window.appReady === true);

The second difference is how they extend. An interface uses extends, a type uses the intersection &. They look alike but behave differently when fields conflict, and the example below shows it.

Example: conflicting fields. There is a base model, and a new one extends it with a different type of the id field (someone moved to numeric ids).

One conflict, two behaviours

Wrong

type + intersection

No error at the declaration. The field becomes never, and the failure shows up later, in every test that uses it.

Right

interface extends

The compiler stops at the declaration and names both types. The mismatch is visible before the first test.

Figure 1. A field conflict when extending: an intersection stays silent, extends checks.
type Base = { id: string };
type Order = Base & { id: number };
// no error: id is now string & number, i.e. never

const o: Order = { id: 1 };
// the error is here, at every use, not at the declaration

Why. An intersection does not check consistency, it just computes the field type as string & number, i.e. never: a value that does not exist. The error shows up where something is put into it. extends demands that the new declaration be a subtype of the base one and refuses at once:

interface Base { id: string }
interface Order extends Base { id: number }
// an error right at the declaration:
// Interface 'Order' incorrectly extends interface 'Base'

The third difference is less obvious and bites in test utilities. A type alias of an object literal implicitly gets an index signature, an interface does not. So a value of an interface cannot be passed to a function taking Record<string, unknown>, while a type can:

interface Account { id: string; iban: string }
type Transfer = { from: string; to: string };

function logRow(row: Record<string, unknown>) {
  console.table(row);
}

declare const acc: Account;
declare const tr: Transfer;
logRow(tr); // ok
logRow(acc); // error: index signature is missing

How to choose. That leaves four questions: do you need a union or a tuple (then type), do you extend someone else's type (then interface with merging), is the value passed to code that expects an index signature (then type), is there a hierarchy of models (then interface extends gives early errors). In addition, the official compiler performance advice prefers extends over intersections for big hierarchies, since the compiler caches the result.

What to default to

interface

Models and contracts

API objects, classes (implements), extending foreign types, hierarchies.

type

Everything that is not an object

Unions, tuples, literals, utility types, values for Record<string, unknown>.

Figure 2. A neutral choice: both options are legitimate, the tasks differ.

Limits and alternatives. Neither option checks data at runtime: both vanish after transpilation. So for API responses a schema (zod, ajv) confirms the shape, and the type is derived from it. Another path: implements works with both. To stop arguments in review, the style is enforced with the ESLint rule @typescript-eslint/consistent-type-definitions: it requires one syntax (interface by default) for all object types, so exceptions such as models for Record<string, unknown> get an eslint-disable comment.

Common mistakes.

  • Describing objects with an intersection instead of extends: a field conflict is invisible, the field silently becomes never.
  • Trying to extend a global type with type: an interface and declare global in a module file are needed.
  • Accidentally declaring two interfaces with the same name in the global scope (files without import/export, or declare global blocks): they merge and the fields of one appear in the other. In module files each interface is separate.
  • Mixing styles with no rule: time is wasted in review and the IDE hints become inconsistent.

Check yourself

Two global .d.ts files of a test utility library declare interface Config with their own fields, and code in a third file suddenly sees all the fields. A bug or a feature?

Answer

This is declaration merging: interfaces with the same name in a shared scope merge. It is needed for extending a library type, and accidental otherwise. To avoid it, use different names or type, which refuses the duplicate.

Why does log(row: Record<string, unknown>) accept a value of type Transfer = {...} but reject an interface Account value with the same fields?

Answer

For aliases of object literals TS infers an implicit index signature, for interfaces it does not, because they can be extended by merging and the new fields may have another type. The fix: type for such models or an explicit index signature.

In an interview. Junior: For an object shape they are almost the same. type can do unions, tuples and primitives, while interface can do merging and extends. Middle/Senior: The choice has consequences: on a field conflict extends fails at the declaration and an intersection silently gives never; an interface has no implicit index signature; merging is needed to extend global types. So I use interface for models and classes, type for the rest, and enforce the default style with a linter.

Optional, undefined and null

An optional field means the key may be absent, | null means the key is present but empty, and | undefined describes in-memory state, not JSON. JSON has no undefined: JSON.stringify drops such fields, so an absent key and null are different contract signals. A type should describe the contract exactly, which strict compiler options such as strictNullChecks help with, and in tests ! is better replaced by an assertion function.

TypeScript · Objects

A "clear the phone" test is green, yet an empty object went to the server. Where did the null go?

The contract says a PATCH with {"phone": null} clears the number, and an absent key leaves it unchanged. An automation engineer writes an object with phone: undefined, the test passes, yet the server never received a clear request. "The field can be empty" has three distinct forms in TypeScript, and each matches a separate situation in JSON. The lesson shows how to tell them apart so the type describes the real contract.

How it works and why. ? means the property may be absent; reading an absent property gives undefined. nick: string | undefined requires the key to exist, but its value may be undefined. closedAt: string | null means the key is always present and null is an explicit "empty" value. JavaScript itself has undefined, but JSON does not: JSON.stringify skips properties whose value is undefined and keeps null. That is why, for an API, the difference between an absent key and null matters.

interface Customer {
  id: string;
  phone?: string; // the key may be absent
  nick: string | undefined; // the key is there, the value may be undefined
  closedAt: string | null; // the key is always there, null means "not closed"
}
Field typeKey in JSONWhat it means
phone?: stringmay be absentvalue not set
nick: string | undefinedrarely makes sense in JSONin-memory state, not on the wire
closedAt: string | nullalways presentan explicit "no value"

The compiler helps only when the options are on. strictNullChecks (part of strict) makes null and undefined separate types; without it they can be assigned to anything. exactOptionalPropertyTypes forbids assigning an explicit undefined to a ? field unless undefined is listed in the type. noUncheckedIndexedAccess adds | undefined to index access, so rows[0].amount on an empty array no longer compiles without a check.

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

Example: "clear the phone". The type lets you write something that vanishes on the wire:

undefined or null in a PATCH

Wrong

{ phone: undefined }

The key never reaches the JSON. The server sees an empty PATCH and changes nothing, while the test does not check the result.

Right

{ phone: null }

The key goes into the JSON with null. The type string | null says plainly that this is a clear command.

Figure 1. What reaches the server: undefined vanishes, null stays.
interface CustomerPatch {
  phone?: string;
}

// goal: clear the phone
const patch: CustomerPatch = { phone: undefined };

await request.patch('/api/customers/7', { data: patch });
// {} goes over the wire: JSON.stringify drops undefined

Without exactOptionalPropertyTypes this compiles: phone?: string allows undefined. With the option there is an error, and the author must decide what they want: drop the key or send null. The fix states the command explicitly in the type:

interface CustomerPatch {
  phone?: string | null; // null = clear, absent = leave alone
}

const patch: CustomerPatch = { phone: null };
await request.patch('/api/customers/7', { data: patch });
// {"phone":null} goes over the wire

The same goes for responses: if the contract says "closedAt is always present", the test must check that rather than smooth it over with ??:

const body: unknown = await res.json();
// the only way to tell "absent" from "null"
expect(body).toHaveProperty('closedAt');
expect(body).toMatchObject({ closedAt: null });

Limits and alternatives. Types describe expectations, not reality: a server response from res.json() has to be checked at runtime. The ! operator (non-null assertion) tells the compiler "trust me" and checks nothing; in tests an assertion function is better, since it fails with a message and narrows the type:

function assertDefined<T>(v: T, msg: string): asserts v is NonNullable<T> {
  if (v === undefined || v === null) throw new Error(msg);
}

const row = rows.find((r) => r.txId === id);
assertDefined(row, 'transaction ' + id + ' not found');
row.amount; // no ? and no !

expect(x).toBeDefined() gives a clear failure but does not narrow the type. The ?. and ?? operators are safe in application code, but in checks they can hide a contract regression: body.closedAt ?? null makes an absent field look like null.

Common mistakes.

  • Describing a "always present, may be null" contract as ?: a regression where the backend stops sending the key goes unnoticed.
  • Passing undefined to clear a field: JSON.stringify drops it.
  • Turning strictNullChecks off "to make it compile": half the value of types disappears.
  • Using ! instead of a check: the failure moves from a clear message to "Cannot read properties of undefined".

Check yourself

The API returns { "id": "1" } without closedAt, and the test has expect(body.closedAt ?? null).toBeNull(). Why is it green, and is that right if the contract requires "closedAt": null?

Answer

The ?? operator turns an absent value into null, so the check cannot tell "no key" from "key is null". For an "always present" contract, check the key (toHaveProperty) and the value separately.

What is the difference between phone?: string and phone: string | undefined, and which of them makes sense for a JSON contract?

Answer

The first allows the key to be absent, the second requires the key with a value that may be undefined. JSON has no undefined, so a meaningful contract is either an absent key (?) or an explicit null.

In an interview. Junior: ? means the field may be missing, while | null means the field is there but empty. Middle/Senior: For an API these are different signals, and the type must match the contract exactly. I keep strict (on by default since TypeScript 6.0), turn on exactOptionalPropertyTypes and noUncheckedIndexedAccess, remember that JSON.stringify drops undefined, and use assertion functions instead of !.

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. The emitted JS has no protection: it 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.