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

TypeScript › Type narrowing and type guards

Discriminated unions

A discriminated union is a union of object types with a shared literal property, and checking it narrows the whole variable to one variant. Invalid field combinations do not compile, and an assertNever that takes never in the default branch makes a new variant highlight every place to update. The discriminant must be a literal, not a wide string. At runtime nothing is guaranteed, so network data is checked with a schema.

TypeScript · Narrowing

A new "crypto" payment method appeared and the report helper stays silent. How do you make the compiler show every place?

A payment can be a card, an IBAN transfer or a wallet, and each method has its own fields. If you describe that with one type full of optional fields, helpers start demanding ! and a new method quietly drops out of every if. A discriminated union solves both problems: the type describes exactly the allowed combinations of fields, and the compiler watches that every variant is handled.

How it works and why. A discriminated union is a union of object types with a shared literal property (the discriminant): kind, status, ok. Checking that property (===, switch) narrows the whole variable to one variant, and the fields of that variant become available without !. It works because every variant has a unique literal value: the compiler sees which variants remain for each value. The discriminant can be a string, a number, a boolean, null or undefined, but not the wide type string: with that the variants cannot be told apart.

Example: from optional fields to a union. First, one type with optional fields:

One type or a union

Wrong

A pile of optional fields

You can build a payment with no field at all or with all of them. Every helper uses ! and nobody notices a new method.

Right

A union with a discriminant

Impossible states cannot be represented. Fields are available without ! after checking kind.

Figure 1. A union leaves impossible field combinations out of the type; one type with optional fields allows them.
interface Payment {
  kind: string;
  pan?: string;
  iban?: string;
  walletId?: string;
}

function describe(p: Payment): string {
  if (p.kind === 'card') return 'Card *' + p.pan!.slice(-4);
  return 'IBAN ' + p.iban!;
}

Here ! removes the compiler check and there is no branch for the wallet at all. With a union the code reads and is checked:

1type Payment =
  | { kind: 'card'; pan: string }
  | { kind: 'iban'; iban: string }
  | { kind: 'wallet'; walletId: string };

function assertNever(x: never): never {
  throw new Error('Unhandled: ' + JSON.stringify(x));
}

function describe(p: Payment): string {
2  switch (p.kind) {
    case 'card':
      return 'Card *' + p.pan.slice(-4);
    case 'iban':
      return 'IBAN ' + p.iban;
    case 'wallet':
      return 'Wallet ' + p.walletId;
    default:
3      return assertNever(p);
  }
}
  1. The union lists the allowed combinations: every variant has its own kind and fields.
  2. switch on the discriminant narrows p in every branch.
  3. In default the variable has type never: if a variant is forgotten, the call will not compile.

The never trick is called an exhaustiveness check. Extend the type and the compiler points at each place that needs an update:

A new variant and exhaustiveness

1. Add { kind: "crypto" }one place in the type2. assertNever(p) does not compilep is not never yet: crypto remains3. Add case "crypto"p narrows to never4. The error disappearsno switch is forgotten
Figure 2. Until the branch is added assertNever does not compile: a variant cannot be forgotten.
type Payment =
  | { kind: 'card'; pan: string }
  | { kind: 'iban'; iban: string }
  | { kind: 'wallet'; walletId: string }
  | { kind: 'crypto'; address: string };

// in describe: assertNever(p)
// Argument of type '{ kind: "crypto"; address: string; }'
// is not assignable to parameter of type 'never'

The same applies to API responses. A boolean ok field is a discriminant too:

type ApiResult<T> =
  | { ok: true; data: T }
  | { ok: false; error: { code: string; message: string } };

function unwrap<T>(res: ApiResult<T>): T {
  if (!res.ok) {
    throw new Error(res.error.code + ': ' + res.error.message);
  }
  return res.data; // here res is the ok: true branch
}

Limits and alternatives. Without default and with an annotated return type, strict also shows that the function may return undefined if switch does not cover every variant, but assertNever gives a clear message and works at runtime if the data turns out different. That is another limit: the union exists only in the compiler. A value from the network with an unknown kind will reach default, so outside data is checked by a schema. zod has z.discriminatedUnion for that, and the type is derived from it:

const Payment = z.discriminatedUnion('kind', [
  z.object({ kind: z.literal('card'), pan: z.string() }),
  z.object({ kind: z.literal('iban'), iban: z.string() }),
]);
type Payment = z.infer<typeof Payment>;

Common mistakes.

  • A discriminant of type string: variants are indistinguishable and narrowing does not work. Literals are needed.
  • switch without a default using never: a new variant is silently skipped.
  • A type with optional fields instead of a union and ! in helpers: the compiler does not help.
  • Checking the variant through if (p.pan) instead of the discriminant: it does not work for a union where the field is not in all variants.

Check yourself

A variant { kind: 'crypto' } was added to the union and describe with default: return assertNever(p) stopped compiling. A bug or a benefit?

Answer

A benefit. In default p is now { kind: 'crypto' } and not never, so the compiler demands a branch. That is how all places needing an update are found.

Why is type Status = { status: string; error?: string } worse than the union { status: 'ok' } | { status: 'error'; error: string } for an API response?

Answer

The first allows "error" without a message and "ok" with one, and after checking the status the field stays optional. In the union the message is required where it exists and absent where it does not.

In an interview. Junior: It is a union with a shared literal field such as status or kind; checking the field narrows the whole object. Middle/Senior: Invalid combinations of fields simply do not compile, and assertNever in default turns exhaustiveness into a compiler check: a new variant instantly lights up every place. Data from the network I check with a schema, since a union guarantees nothing at runtime.

More articles in this chapter