Skip to content
Visual explainer 4h to learn 5 steps

Unions, narrowing & generics

Model states with discriminated unions and write reusable generic helpers.

By Invicly Tech, , in Frontend with React & Next.js. About 11 minutes to read.

Topic 11 of 36

In short

Union types say a value can be one of several types, and narrowing lets TypeScript know which one you have. Generics let one function or type work with many types while staying type safe.

Explained simply

Sometimes a value can be one of a few things. An id might be a number or a string. A request might be loading, finished, or failed. TypeScript writes this with a union type, using the | sign: string | number means either one.

Before you use a union value, you usually need to know which one you have. If you check typeof id === "string", TypeScript understands that inside the if block id is a string. This is called narrowing: the type gets smaller as you learn more.

A discriminated union is a union of objects that all share one field with a fixed value, often called status or kind. Checking that one field tells TypeScript exactly which object you have and which other fields exist. It is the cleanest way to model screens that can be in several states.

Generics are type placeholders, usually written T. A generic function like first(items) works for a list of numbers or a list of users and still knows what it returns. You write the logic once and keep full type safety for every caller.

Press Play on a diagram to walk through it one step at a time.

MapA discriminated union for request state
RequestState
  • status: 'idle'
  • status: 'loading'
  • status: 'success'
    • data: T
  • status: 'error'
    • error: string
MapUtility types by job
Utility types
  • Change every field
    • Partial
    • Required
    • Readonly
  • Choose fields
    • Pick
    • Omit
  • Build objects
    • Record (keys to values)
  • Read functions
    • ReturnType
    • Parameters
    • Awaited
  • Filter unions
    • Exclude
    • Extract
    • NonNullable
CompareBoolean flags vs a discriminated union
isLoading, isError, data?
  • 4 flag combinations are possible
  • isLoading and isError can both be true
  • data may be undefined even on success
  • Every reader must guess the rules
status: "loading" | "success" | "error"
  • Exactly one state at a time
  • data exists only in the success variant
  • switch narrows each branch
  • never check catches missing cases

In depth

How narrowing really works

TypeScript follows your code paths, a technique called control-flow analysis. At each line it tracks what the type of a variable can still be. A check removes possibilities: after if (value === null) return, the rest of the function knows value is not null.

Many checks narrow: typeof for primitives, === against a literal, truthiness (if (name)), the in operator ("email" in contact), instanceof for classes like Date or Error, and Array.isArray. One trap: typeof null is "object", so typeof x === "object" does not exclude null. Another: a truthiness check also removes 0 and the empty string, which may be valid values.

  • typeof for string, number, boolean, function
  • in for checking that a field exists
  • instanceof for classes like Error and Date
  • Early return narrows everything after it
FlowNarrowing string | number | null step by step
  1. Step 1
    Start

    value: string | number | null

  2. Step 2
    if (value === null) return

    After this: string | number

  3. Step 3
    if (typeof value === "number")

    Inside: number

  4. Step 4
    Else branch

    Only string is left

Your own type guards

Sometimes the check is too complex for TypeScript to follow, for example validating an object from an API. You can write a type guard: a function whose return type is value is Fish. When it returns true, TypeScript narrows the argument to Fish in the caller.

Be careful: TypeScript trusts your guard completely. If the function body is wrong, the narrowing is wrong too. Keep guards small and test them.

Since TypeScript 5.5, simple arrow functions get an inferred type predicate. That means items.filter((x) => x !== undefined) now returns an array without undefined, which used to need a hand-written guard.

Exhaustive checks with never

never is the type of something that cannot happen. After you handle every case of a union in a switch, the variable in the default branch has type never. You can use this to make the compiler remind you about new cases.

Assign the value to a variable typed never in the default branch. Today it compiles. When a teammate adds status: "cancelled" to the union and forgets to handle it, that line becomes an error that points straight at the switch that needs updating. This turns a silent runtime bug into a compile error, which is exactly what types are for.

  • const unreachable: never = state;
  • Adding a variant breaks the build until it is handled
  • Works for switch and if/else chains

Generics: constraints and keyof

A generic says: the type here is decided by the caller, and these types are linked. In first<T>(items: T[]): T | undefined, the T in the input and output must be the same, so first([1, 2]) returns number | undefined.

Often you need T to have some feature. A constraint does this: T extends { id: string } means any type with an id field. keyof T is the union of T's property names, so getField<T, K extends keyof T>(obj: T, key: K): T[K] only accepts real keys and returns the right field type.

A good rule: a type parameter should appear at least twice, to connect things. If T is used only once, a plain type is simpler.

Built-in utility types

Utility types build new types from existing ones, so you do not copy and paste shapes. Partial<T> makes every field optional, which fits update forms. Required<T> does the opposite. Readonly<T> blocks reassignment. Pick<T, "id" | "name"> keeps some fields and Omit<T, "password"> drops some. Record creates an object type from a key type and a value type.

For functions, ReturnType and Parameters (used with typeof fn) extract the result and argument types, and Awaited unwraps a Promise. NonNullable removes null and undefined, and Exclude and Extract filter unions. Deriving types this way means a change to the base type flows everywhere automatically.

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Write union and literal types~50m
  2. 2
    Narrow types with typeof and in~50m
  3. 3
    Model state with discriminated unions~50m
  4. 4
    Write generic functions and types~50m
  5. 5
    Use built-in utility types~50m

Key points

  • A discriminated union shares one literal field, like status, to tell variants apart.
  • Checking typeof, in, or the discriminant narrows the type inside that branch.
  • Generics like <T> keep the link between input and output types.
  • Utility types like Partial, Pick and Omit derive new types from existing ones.

Key terms

Tap a card to flip it. 0/5 known

Examples

ts
type State<T> =
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: string };

function render(s: State<string[]>): string {
  switch (s.status) {
    case 'loading': return 'Loading...';
    case 'success': return s.data.join(', ');
    case 'error': return `Error: ${s.error}`;
  }
}

const first = <T,>(items: T[]): T | undefined => items[0];

Narrowing by status, plus a small generic helper.

A payment result with an exhaustive switch

A checkout can end in three ways. Step 1: model them as a union with a shared kind field. Step 2: switch on kind; in each case TypeScript knows exactly which fields exist, so result.receiptUrl is only allowed in the paid case. Step 3: the default branch assigns to never. If someone adds a "refunded" variant later, this file stops compiling until they handle it.

ts
type PaymentResult =
  | { kind: "paid"; receiptUrl: string }
  | { kind: "declined"; reason: string }
  | { kind: "pending"; retryInMs: number };

function message(result: PaymentResult): string {
  switch (result.kind) {
    case "paid": return "Thanks! Receipt: " + result.receiptUrl;
    case "declined": return "Card declined: " + result.reason;
    case "pending": return "Still processing...";
    default: {
      const unreachable: never = result;
      return unreachable;
    }
  }
}

A generic groupBy helper

You often need to group a list, such as orders by status. Step 1: make the item type generic, T, so it works for any list. Step 2: constrain the key K to string because it becomes an object key. Step 3: take a function that picks the key. The result is typed as an object of T arrays, so grouped.paid is Order[] with full autocomplete. Since ES2024, Object.groupBy does the same at runtime in modern browsers.

ts
function groupBy<T, K extends string>(
  items: T[],
  keyOf: (item: T) => K,
): Partial<Record<K, T[]>> {
  const out: Partial<Record<K, T[]>> = {};
  for (const item of items) {
    const key = keyOf(item);
    (out[key] ??= []).push(item);
  }
  return out;
}

type Order = { id: number; status: "paid" | "open" };
const orders: Order[] = [{ id: 1, status: "paid" }, { id: 2, status: "open" }];
const grouped = groupBy(orders, (o) => o.status); // grouped.paid: Order[] | undefined

Quick reference

  • A | B means the value is one of them; narrow before using type-specific features
  • typeof null is "object": check for null separately
  • Give every union variant the same literal field (kind or status) to discriminate it
  • In a default branch, const x: never = value catches unhandled variants
  • function isUser(v: unknown): v is User declares a custom type guard
  • K extends keyof T restricts K to real property names of T
  • Partial, Pick and Omit derive types instead of copying shapes
  • If a type parameter appears only once, you probably do not need a generic

Common mistakes

  • Modelling state with several optional booleans that can contradict each other.
  • Writing generics that are never used to relate inputs and outputs.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1value has type string | null. Inside if (typeof value === "object") { ... }, what is its type?

Question 2

2What makes a union a discriminated union?

Question 3

3What does Omit<User, "password"> produce?

Question 4

4Why add K extends keyof T in getField(obj, key)?

Question 5

5What happens when a new variant is added to a union that is switched over with a never check in the default branch?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write describe(input: string | number | boolean) that returns "text", "number" or "flag" using typeof checks.

  2. Exercise 2medium

    Model a file upload as a discriminated union: idle, uploading with a progress number, done with a url, and failed with an error message. Write label(state) that returns a short text for each state.

  3. Exercise 3hard

    Write a generic pluck(items, key) that returns an array of the values of that key, typed correctly. pluck(users, "email") should be string[], and pluck(users, "nope") should not compile.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between a union and an intersection type?
A union A | B is either A or B. An intersection A & B must be both at once, so it has all the fields of A and B combined.
When should I use a generic instead of any?
Whenever the output type depends on the input type. A generic keeps that link, while any throws the type information away.
Why does TypeScript forget my narrowing inside a callback?
A callback may run later, after the variable has changed. Copy the narrowed value into a const before the callback, and TypeScript keeps the narrowed type.

Go deeper

ShareXLinkedInWhatsApp