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

TypeScript

Basics: primitives, any, unknown, never, literals

Why TypeScript in a test framework

TypeScript gives autocompletion, safe refactoring and early errors, but types exist only at development time and vanish at runtime. So they do not validate an API response: at the network boundary take data as unknown and narrow it with a check or a schema, not as. Playwright only transpiles TS without type checking, so CI needs a separate tsc --noEmit step, and tsconfig needs strict.

TypeScript · Basics

The Transfer type is defined, the test compiles, yet the sum is glued as a string. Why is TypeScript silent?

A test framework has a Transfer type with amount: number. A test takes an API response, adds the amount and the fee and compares the result with the expected value. Everything compiles, the editor underlines nothing, and the test fails: the server returns the amount as the string "100.50", so instead of addition there is concatenation. The type "lied" and nobody noticed. This lesson is about what TypeScript guarantees, what it does not, and how to build a test framework so that types really help.

How it works and why. TypeScript is JavaScript with a type system that works only at development time. Types, interfaces and annotations do not reach the executable code: after transpilation plain JS remains. This is a deliberate design: TS is added to existing JS without changing the runtime, so it knows nothing about what actually arrives from the network. A second consequence matters more for QA: Playwright transpiles TS but does not check types (its documentation says so). A test with a type error can run happily. Types are checked by a separate step, tsc --noEmit, and its place is in CI and in the editor.

Where types live

.ts codetypes, interfaces, annotationsRun by Playwrighttypes are stripped, not checkedtsc --noEmittypes are checked here (and in the editor)Runtimeno types, nobody knows the API shape
Figure 1. Only tsc checks types. The runner strips them, and at runtime nobody compares an API response with the interface.

What this gives an automation engineer once the tsc step is set up. Autocompletion for Page Objects, fixtures and API clients: a new engineer sees which methods exist and what they accept. Safe refactoring: rename the accountId field and the compiler shows every broken test. The TransferRequest type documents the contract better than a comment. Early errors: a typo in a field name, undefined where a string is expected, a promise result used as a value without await. A bare call without await passes the compiler; the ESLint rule @typescript-eslint/no-floating-promises catches it.

Basic primitives: string, number, boolean, null, undefined, bigint, symbol. Arrays are written string[] or Array<string>, tuples [string, number]. You do not annotate every variable: TS infers the type. Annotations go on boundaries: function parameters, the values public methods return, data models. "strict": true in tsconfig turns on, among others, noImplicitAny and strictNullChecks. Without it half of the value is lost, so a new project has it on from day one.

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

Example: the code compiles and a bug hides. A typical test checks a transfer sum with a fee:

interface Transfer {
  id: string;
  amount: number;
  fee: number;
}

test('total with fee', async ({ request }) => {
  const res = await request.post('/api/transfers', { data: { amount: 100.5, fee: 0.05 } });
  const body = (await res.json()) as Transfer;
  const total = body.amount + body.fee;
  expect(total).toBe(100.55);
});

What is wrong here. The as Transfer line checks nothing: it is a promise to the compiler "trust me, the shape is this". res.json() in Playwright does not know the response shape (in the types it is a value with no checked structure, effectively any), so as always passes. If the server returns amount as a string, body.amount + body.fee gives the string "100.500.05", not a number. The test fails comparing a string with a number, and the cause has to be found by hand: the error points at the test, not at the mismatch between the type and the contract.

The fix is to move the check to where data enters the framework: accept the response as unknown and narrow the type with an explicit check.

function isTransfer(v: unknown): v is Transfer {
  if (typeof v !== 'object' || v === null) return false;
  const t = v as Record<string, unknown>;
  return (
    typeof t.id === 'string' &&
    typeof t.amount === 'number' &&
    typeof t.fee === 'number'
  );
}

const body: unknown = await res.json();
if (!isTransfer(body)) {
  throw new Error('Not a Transfer: ' + JSON.stringify(body));
}
const total = body.amount + body.fee;

Now the mismatch is caught on the very first response, and the message contains the raw data. After that body has the type Transfer without any as, because the compiler sees that the check passed. For large models the function is not written by hand: a schema (zod, ajv) gives both the runtime check and the type from one description. The principle is the same: a type describes an expectation, and a runtime check confirms that the data matches it.

Trusting API data

Wrong

as Transfer

The type is declared, not verified. The error shows up later in the test and looks like a logic failure.

Right

unknown and a check

The mismatch is visible at once on input, the message carries the raw data, and afterwards the type is real.

Figure 2. A type in code is only an expectation. Data from outside is checked at runtime.

Limits and alternatives. Types do not replace tests and do not check the runtime: they prove only that the code is consistent with itself. A wrong type written by hand will not be exposed by the compiler. So the value is not in the number of annotations but in their accuracy and in the boundaries where they are confirmed by data. Typing has a cost: more code, a slower start for a new engineer, the need to keep types up to date. In small scripts and one-off checks, JS without types is a reasonable choice. For a framework that lives for years and is changed by many people, types pay off during refactors. A gradual path exists: allowJs and migration file by file.

Common mistakes.

  • Assuming Playwright catches type errors itself: it only transpiles, so without tsc --noEmit in CI type errors reach the test run.
  • as Type on an API response: there is no check, and the promise to the compiler becomes a source of false confidence.
  • strict turned off: undefined and null stop being part of the type and half the errors slip through.
  • Annotating everything: noise with no benefit, because TS infers the type anyway.
  • Types without upkeep: the model lags behind the API and "safe" code is safe on paper only.

Check yourself

A test with const body = (await res.json()) as Transfer is green locally, but CI shows the server returns amount as a string. Why did neither TypeScript nor the editor say so?

Answer

Because as is an assertion to the compiler, not a check. Types are erased after transpilation, and at runtime no code compares the response with the interface. The fix: accept the response as unknown and verify the shape (a guard or a schema) on input.

A test has an obvious type error, yet npx playwright test runs it. Is Playwright set up wrongly, and what should be done?

Answer

There is no mistake: Playwright transpiles TS without checking types. Add type checking as a separate tsc --noEmit step in CI (and in the editor), so errors are caught before the tests run.

In an interview. Junior: TypeScript catches errors before the tests run, gives autocompletion and makes the framework self-documenting. Types exist only at compile time and disappear at runtime. Middle/Senior: Types do not verify an API response, so at the network boundary I accept data as unknown and narrow it with a check or a schema instead of writing as. I also remember that Playwright does not check types: CI has a separate tsc --noEmit step and strict is on in tsconfig.

any, unknown and never

any switches type checking off, unknown accepts any value but must be narrowed before use, and never is a type with no values. Any infects the code around it, so external data is taken as unknown and narrowed with a guard or a schema. Never underlies exhaustiveness checks: in a default branch the variable is passed to assertNever(x: never), so an unhandled new status breaks the build.

TypeScript · Basics

An API response is parsed as any, the test compiles and fails on undefined. How do we make the compiler help?

An API response is parsed as any, the code has the line data.acount.id with a typo, and the compiler is silent. The test fails at runtime on undefined although the project is TypeScript. There is also the reverse story: a new status REVERSED was added to a switch over a transfer status, while a function that expects "in progress", "done", "failed" quietly returns "failed" for everything unknown. This lesson is about three types that control how much data is trusted: any, unknown and never.

How it works and why. any is a switched-off type check. With an any value you can do anything: access properties, call it as a function, pass it anywhere. Worse, it "infects": the result of anyValue.foo.bar is also any, and distrust of types spreads along the chain. any exists as an escape hatch for migrating from old JS, not as a convenient type.

const data: any = await res.json();
const id = data.acount.id;
console.log(id.toUpperCase());

This fragment compiles fully. The typo acount turns into undefined, and the next line fails with an error about calling a method on undefined, far from the real cause. unknown is the safe version: you can put anything into the variable, but cannot use it before checking. The compiler demands narrowing: typeof, instanceof, in, a custom type guard or a schema.

In strict mode (strict, precisely useUnknownInCatchVariables) the variable in catch is also unknown: anything can be thrown, not only an Error.

try {
  await doWork();
} catch (e) {
  // e is unknown under "strict"
  const msg = e instanceof Error ? e.message : String(e);
  console.error(msg);
}

never is a type with no values. It is returned by a function that always throws or never finishes. It is also the "bottom" of the hierarchy: a value of type never can be assigned anywhere, while only never can be assigned to never. Exhaustive checking rests on this: in the default branch the variable has type never only if every variant of the union has already been handled.

Types from top to bottom

unknowntop: accepts any value'PENDING' | 'FAILED'union: several allowed values'PENDING'a single literalneverbottom: no values at all
Figure 1. unknown accepts everything but gives nothing back without a check. never has no values, so the union variants "run out" in it. any stands outside the diagram: it switches the hierarchy off.

Example: the code compiles and a bug hides. A test helper returns the expected badge of a transfer status:

type Status = 'PENDING' | 'COMPLETED' | 'FAILED';

function expectedBadge(s: Status): string {
  switch (s) {
    case 'PENDING':
      return 'In progress';
    case 'COMPLETED':
      return 'Done';
    default:
      return 'Failed';
  }
}

While there are three statuses everything works. When the backend adds REVERSED and the Status type is updated, the function keeps compiling: the default branch quietly returns "Failed" for a reversed transfer. A test with it either passes wrongly or fails with a mismatch whose trail leads the wrong way. This scenario is dangerous precisely because nothing turns red.

The fix is to make default the "this cannot happen" branch and leave it to the compiler:

type Status = 'PENDING' | 'COMPLETED' | 'FAILED' | 'REVERSED';

function assertNever(x: never): never {
  throw new Error('Unhandled status: ' + String(x));
}

function expectedBadge(s: Status): string {
  switch (s) {
    case 'PENDING':
      return 'In progress';
    case 'COMPLETED':
      return 'Done';
    case 'FAILED':
      return 'Failed';
    case 'REVERSED':
      return 'Reversed';
    default:
      return assertNever(s);
  }
}

If another variant appears in Status and no branch is added for it, assertNever(s) receives a value that is not never, and the compiler reports something like "Argument of type '"ARCHIVED"' is not assignable to parameter of type 'never'". The code stops building until the status is handled. There is a second protection, at runtime: if the server returns a value that is not in the type, assertNever throws a clear error instead of a quiet wrong result.

What default does in a switch

Wrong

default: return 'Failed'

A new status lands in someone else value. The build is green, the error is visible only by chance.

Right

default: assertNever(s)

A new status breaks the build, and an unknown value from the server gives a clear runtime error.

Figure 2. An exhaustive check turns "we forgot to handle it" into a compile error.

Reading the error: an unhandled value in a switch

1src/badge.ts(18,26): error TS2345: 2Argument of type '"ARCHIVED"' is not assignable to 3parameter of type 'never'.
  1. Where: file, line and column: the assertNever(s) call in the default branch.
  2. Cause: the variant "ARCHIVED" is left in s and has no case branch.
  3. Why: assertNever accepts only never, and the leftover value is not never. This is how the compiler reports unfinished handling.

What to do

Add a case 'ARCHIVED' with the right badge. Do not silence the error with as never or @ts-expect-error: it points at exactly the missed case.

Figure 3. The tsc output (shortened, without the line excerpt): the numbers lead to the explanations.

Limits and alternatives. An exhaustive check works only when the Status type agrees with the real API: a union written by hand can lag behind. For data from the outside world unknown is only the beginning; a real check (a guard or a schema such as zod) is needed next. as narrows a type without checking, so (x as Foo) brings back the same danger as any, only locally. To enforce discipline in the project, turn on the ESLint rule @typescript-eslint/no-explicit-any, and the type-checked rule set adds a ban on unsafe operations with any values (no-unsafe-*). An alternative to an exhaustiveness check through never is satisfies or a Record<Status, string> object where the compiler requires all keys.

Common mistakes.

  • const data: any = await res.json(): the check is off and typos in fields show up at runtime. Prefer unknown and narrowing.
  • as Foo on external data: the same any, only looking like a check.
  • A default with a "smart" value in a switch over a union: a new status slips through unnoticed.
  • catch (e) reading e.message without a check: in strict mode e is unknown.
  • Confusing never with void: a void function finishes and returns nothing, while a never function never returns.

Check yourself

After adding REVERSED to Status the project builds without errors, although the function has default: return 'Failed'. Why, and what changes so that the build fails?

Answer

The default branch has no exhaustiveness check, so any unknown status simply lands in "Failed". The default must pass the variable to a function that accepts never (assertNever(s)): then unfinished handling becomes a compile error.

The code catch (e) { console.log(e.message) } gets an error under strict. Why, and how is it fixed?

Answer

Under strict the variable in catch has type unknown, because anything can be thrown. Narrow it: e instanceof Error ? e.message : String(e).

In an interview. Junior: any turns type checking off, while unknown is safer: it must be narrowed before use. never is a type with no values, used in an exhaustive switch. Middle/Senior: For external data I take unknown and narrow it with a guard or a schema, and I ban any with an ESLint rule. In a switch over statuses, default calls assertNever: a new status breaks the build, and an unknown value from the server gives a clear runtime error.

Literal types, as const and satisfies

A literal type has one specific value, and a union of literals describes a finite set, so 'usd' instead of 'USD' does not compile. The as const assertion makes a value immutable with exact types, giving one source of truth for a union. The satisfies operator checks a value against a type without replacing its inferred type. All of this is compile-time only, so API data is validated at runtime.

TypeScript · Basics

A test passes "usd" instead of "USD" and the API answers 400. Why did the compiler not stop it?

A test opens an account in a currency. The parameter is described as string, so 'usd', 'Usd' and 'UAH ' with a trailing space all compile, and the API returns 400. The type does not tell a valid string from an arbitrary one. Literal types make the contract precise: a type with one specific value ('GET', 200, true), and a union of literals describes a finite set. This lesson is about how to create them, how not to lose them and how to check test data through as const and satisfies.

How it works and why. type Currency = 'UAH' | 'USD' | 'EUR' allows exactly three values, and 'usd' becomes a compile error. But TS does not always keep the literal. For const method = 'GET' the type is precise: 'GET', because the variable will not change. For let and for object properties the type widens to string: the value can be changed, so TS chooses a general type. That is a sensible choice for code that mutates data and an unneeded nuisance for test constants.

Literal widening

const m = 'GET'type 'GET'let m = 'GET'type string (widening){ method: 'GET' }method: string{ method: 'GET' } as constreadonly method: 'GET'
Figure 1. const keeps the literal. let and object properties widen to string. as const fixes literals and makes fields readonly.

as const tells the compiler: this value is immutable, the type should be as narrow as possible. All fields become readonly, strings stay literals, an array turns into a tuple. A type is derived from such a constant with no duplication:

const ENDPOINTS = {
  accounts: '/api/v1/accounts',
  transfers: '/api/v1/transfers',
} as const;

type Endpoint = (typeof ENDPOINTS)[keyof typeof ENDPOINTS];
// '/api/v1/accounts' | '/api/v1/transfers'

A second technique: an array of values plus a type from it. You get one source of truth: the array is used in parameterised tests and the type in signatures.

const CURRENCIES = ['UAH', 'USD', 'EUR'] as const;
type Currency = (typeof CURRENCIES)[number];

for (const currency of CURRENCIES) {
  test('opens an account in ' + currency, async ({ request }) => {
    await openAccount(request, currency);
  });
}

Add 'PLN' to the array: the type updates, a test for the new currency appears, and nothing is duplicated. The satisfies operator (since TypeScript 4.9) does something else: it checks that a value matches a type but does not replace the value's type with that type. The object keeps its exact keys while the compiler still compares it with the schema.

Example: the code compiles and a bug hides. A dictionary of rates for a conversion check, with a type annotation:

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

const rates: Record<string, number> = {
  UAH: 1,
  USD: 41.5,
  EUR: 45,
};

const wrong = rates.usd; // number, but at runtime undefined
const sum = 100 * wrong; // NaN

The Record<string, number> annotation says "any string is a key". So rates.usd with a case typo compiles and has the type number, although at runtime it is undefined. The calculation then gives NaN, and the test fails far from the typo. On top of that the annotation does not require all three currencies: an EUR removed from the object would pass as well.

The fix is to replace the annotation with satisfies and the listed keys:

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

const rates = {
  UAH: 1,
  USD: 41.5,
  EUR: 45,
} satisfies Record<Currency, number>;

rates.usd; // error: Property 'usd' does not exist
rates.USD; // number

Now the object keys are exact: rates.usd is a compile error, and if EUR is removed from the object, the compiler says a property is missing. The "all currencies are covered" check stays. An annotation : Record<Currency, number> would give the same key check here. The difference shows when the exact type matters: satisfies leaves the variable its inferred type, so { … } as const satisfies Record<Currency, number> keeps USD: 41.5, while the annotation would widen the values to number.

Annotation or satisfies

Wrong

: Record<string, number>

Any key is allowed. A typo gives undefined at runtime, and a missing currency goes unnoticed.

Right

satisfies Record<Currency, number>

The keys are exact. A typo and a missing currency become compile errors.

Figure 2. For test data dictionaries check keys against a union, not against string.

Limits and alternatives. All of this works at compile time only: as const and satisfies check nothing at runtime, so a server response with 'usd' is not stopped by these types. Data from outside needs a runtime check. as const makes an array readonly, and such an array cannot be passed to a function that accepts a mutable string[]: the parameter must be described as readonly string[]. Instead of enum a union of literals is more often chosen: it generates no runtime code, combines naturally with JSON from an API, and the erasableSyntaxOnly flag (since TS 5.8) and running TS without a full transform in modern Node allow only erasable constructs. String enums have their place when a runtime object is needed, but for most test constants a union is simpler.

Common mistakes.

  • Describing currencies, roles and statuses as string: the compiler cannot tell 'usd' from 'USD'.
  • let or an object property without as const: the literal widens to string and the argument does not fit a function with a union.
  • as 'USD' instead of fixing the type: the cast silently bypasses the check.
  • A Record<string, …> annotation for a test data dictionary: key errors are not caught. satisfies exists.
  • Expecting runtime protection from as const: readonly exists only at compile time.

Check yourself

The function createAccount(c: Currency) does not accept demo.currency, where const demo = { currency: 'USD' }, although the value is "USD". Why, and how is it fixed?

Answer

An object property widens to string because it can be changed. The fix: as const on the object (the property becomes 'USD'), or satisfies, or an explicit type annotation on the field.

What changes when : Record<string, number> is replaced with satisfies Record<Currency, number> for a rates dictionary?

Answer

The keys are checked against the union: a typo in a key name and a missing currency become compile errors. The object keeps its exact types, so rates.usd no longer compiles. At runtime nothing changes.

In an interview. Junior: A literal type has a single value, and a union of literals limits a set, for example currencies or statuses. as const makes a value immutable with exact types. Middle/Senior: An as const array gives one source of truth: I derive the union from it and drive parameterised tests with it. I check test data dictionaries with satisfies against a union, so a key typo or a missing currency does not pass. I remember this is compile time only, so API data is checked at runtime. Instead of enum I usually take a union.