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

TypeScript › Basics: primitives, any, unknown, never, literals

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.

More articles in this chapter