TypeScript · Lesson 4 of 7

Union types & narrowing

Values that can be one of several types, literal types and narrowing with checks.

A union type means “one of these”: string | number. Literal types restrict a value to exact options: "pending" | "shortlisted" | "rejected" — far safer than any string.

Before using a union, you narrow it so TypeScript knows which type you have:

  • typeof x === "string" for primitives.
  • "field" in obj or instanceof for objects.
  • A shared kind or status property with switch — a discriminated union, the most useful pattern of all.

Example code

Try it in the TypeScript Playground or with tsc
type Status = "applied" | "interview" | "offer" | "rejected";

type Update =
  | { status: "interview"; date: string }
  | { status: "offer"; salaryLpa: number }
  | { status: "applied" | "rejected" };

function describe(u: Update): string {
  switch (u.status) {
    case "interview":
      return "Interview on " + u.date;
    case "offer":
      return "Offer: " + u.salaryLpa + " LPA";
    default:
      return "Status: " + u.status;
  }
}

console.log(describe({ status: "offer", salaryLpa: 7.2 }));
console.log(describe({ status: "interview", date: "12 Nov" }));
let s: Status = "selected";   // error

Compiler / program output

error TS2322: Type '"selected"' is not assignable to type 'Status'.

(after fixing that line)
Offer: 7.2 LPA
Interview on 12 Nov

Paste the code into the official TypeScript Playground in your browser, or install TypeScript (npm install -D typescript) and run npx tsc --noEmit to type-check. Names are fictional.

Key points

  • Union = one of several types: A | B.
  • Literal types limit values to exact options.
  • Narrow with typeof, in, instanceof or a shared status field.
  • Discriminated unions + switch make state handling safe.

Quick check

Why use "applied" | "offer" instead of string for a status?

Practice task

Model an API result as a discriminated union of { ok: true; data: string[] } and { ok: false; error: string }, and write a function that prints either the data or the error.

Interview corner

What is type narrowing?

Refining a broad type (like string | number) to a specific one inside a code branch using checks such as typeof, instanceof, in, equality or a discriminant property. TypeScript then allows only operations valid for the narrowed type.

What is a discriminated union?

A union of object types that share a literal property such as status or kind. Switching on that property lets TypeScript know exactly which shape you have in each case.

Further reading

Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.

Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.