TypeScript Type Narrowing: Guards, Discriminated Unions, and Real-World Examples
typescripttype-narrowingtype-guardsunion-typeserror-handling

TypeScript Type Narrowing: Guards, Discriminated Unions, and Real-World Examples

TTypeScript.page Editorial Team
2026-12-01
7 min read

Learn when to use typeof, in, instanceof, custom predicates, assertions, and discriminated unions to narrow TypeScript values safely.

TypeScript type narrowing turns an uncertain value into a safely usable one without giving up the protection of static checking. This guide compares built-in guards, custom predicates, assertion functions, and discriminated unions, then applies them to API responses and event handlers so you can choose a reliable narrowing strategy before fixing a property-does-not-exist error.

Overview

Type narrowing is TypeScript's process of refining a broad type into a more specific type after the code proves that a condition is true. It is especially important when a value begins as unknown, comes from an external API, or belongs to a union of several possible object shapes.

Start with unknown rather than any for data you do not control. An unknown value cannot be used until a check establishes what it is. That extra friction is useful: it places validation at the boundary where uncertainty enters the application.

function formatValue(value: unknown): string {
  if (typeof value === "string") {
    return value.trim();
  }

  if (typeof value === "number") {
    return value.toFixed(2);
  }

  return "Unsupported value";
}

TypeScript follows these checks through control flow. In the first branch, value is a string; in the second, it is a number. The safest narrowing technique depends on the shape of the value and the guarantee you need.

TechniqueBest forImportant detail
typeofPrimitive values and functionsUse for strings, numbers, booleans, symbols, bigints, and functions.
inObjects with different propertiesChecks whether a property exists on an object or its prototype chain.
instanceofClass instances and built-in objectsDepends on runtime constructors and can be unreliable across realms.
Custom type predicateReusable structural checksA function returning value is SomeType tells the compiler the result of a valid check.
Assertion functionValidation that throws on failureUse asserts value is SomeType when execution cannot continue after invalid input.
Discriminated unionKnown states or event variantsA shared literal property lets TypeScript select one union member.

Checklist by scenario

When the value is a primitive

Use typeof and handle the JavaScript edge cases deliberately. For example, typeof null is "object", and arrays also satisfy an object check. If you need a non-null object, combine the checks.

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

Checklist: confirm the value is not null, distinguish arrays from records, and narrow properties after the object check rather than assuming they exist.

When union members have different properties

The in operator is useful when object variants do not share a clear status field.

type EmailContact = { email: string };
type PhoneContact = { phone: string };

type Contact = EmailContact | PhoneContact;

function contactLabel(contact: Contact): string {
  if ("email" in contact) {
    return contact.email;
  }

  return contact.phone;
}

Checklist: make sure the property is distinctive enough to identify the branch, avoid using a property that can appear on multiple variants, and remember that an in check confirms presence, not necessarily the property's value type.

When working with class instances

Use instanceof when runtime identity matters and the value is expected to be created by a known constructor.

function readError(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }

  return "Unknown failure";
}

Checklist: use instanceof for actual instances, not plain objects that merely look similar, and consider a structural check when data has crossed a serialization or process boundary.

When handling an API response

An interface does not validate JSON at runtime. Define the expected shape, then write a predicate that checks the fields your application will use.

type User = {
  id: string;
  name: string;
};

function isUser(value: unknown): value is User {
  if (typeof value !== "object" || value === null) {
    return false;
  }

  const record = value as Record<string, unknown>;
  return typeof record.id === "string" && typeof record.name === "string";
}

async function loadUser(response: Response): Promise<User> {
  const body: unknown = await response.json();

  if (!isUser(body)) {
    throw new Error("Unexpected user response");
  }

  return body;
}

The assertion in const record = value as Record<string, unknown> is limited to inspecting an already checked object. It does not claim that the entire API response is valid. The predicate earns its stronger return type by checking each required field.

When an API or application has known states

Prefer a discriminated union when every variant can carry a shared literal property such as status, kind, or type.

type RequestState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; message: string };

function renderState(state: RequestState): string {
  switch (state.status) {
    case "idle":
      return "Ready";
    case "loading":
      return "Loading...";
    case "success":
      return `${state.data.length} results`;
    case "error":
      return state.message;
  }
}

Checklist: use literal values for the discriminator, keep variant-specific fields on the correct member, and make the switch exhaustive as the union grows. This pattern often produces clearer code than several unrelated property checks.

When handling React or DOM events

Use the event type supplied by the framework or platform first, then narrow the target before reading a field that is not shared by every element.

function handleChange(event: Event): void {
  const target = event.target;

  if (!(target instanceof HTMLInputElement)) {
    return;
  }

  console.log(target.value);
}

For framework-specific handlers, use the framework's event type and its target model rather than casting immediately. A type cast may silence an error while leaving a runtime mismatch unchanged.

What to double-check

  • Check the boundary: Validate values when they enter from JSON, query parameters, storage, messages, or third-party code.
  • Prefer narrow checks: A predicate should verify the fields that make its claim true. Do not return true merely because the value is an object.
  • Separate validation from assertion: A boolean predicate lets the caller choose what to do. An assertion function throws or otherwise stops execution when the claim fails.
  • Review compiler settings: Strict null checks and related strictness options make unsafe assumptions visible. If a narrowing result seems surprising, inspect the inferred type in the editor and check the project's TypeScript configuration.
  • Consider runtime behavior: instanceof is based on constructors, while custom predicates are structural. Choose according to how the value was created and transported.
  • Model impossible states: If a state combination should not occur, represent valid combinations as a discriminated union instead of several optional properties.

When investigating a “property does not exist on type” diagnostic, identify the union members first. Then ask whether the property is available on all members, whether a discriminator can select the right member, or whether the incoming value needs runtime validation.

Common mistakes

Using as as a substitute for narrowing

const user = value as User changes the compiler's view but performs no runtime check. Keep assertions close to a proven condition, or replace them with a predicate that can be tested.

Overusing any

any disables the feedback that makes narrowing valuable. If the input is unknown, keep it unknown until a guard establishes a useful type.

Writing a predicate that checks too little

A function declared as (value: unknown): value is User must check enough of the value to justify the claim. An incomplete predicate can make invalid data appear safe throughout the rest of the program.

Assuming optional properties define distinct variants

A type with many optional fields can allow contradictory states. A discriminated union makes the valid relationships explicit and gives control-flow analysis a reliable signal.

Forgetting the default or unreachable case

When a union evolves, code that handled the original variants may become incomplete. Review switches and conditionals whenever a new member is added. An exhaustive helper can make that gap visible:

function assertNever(value: never): never {
  throw new Error(`Unexpected value: ${String(value)}`);
}

When to revisit

Return to this checklist whenever an external payload changes, a new event variant is introduced, or a previously broad value begins carrying more states. It is also worth revisiting during a JavaScript-to-TypeScript migration, a strictness upgrade, or a refactor that replaces optional properties with a union.

Before merging a change, run through these practical steps:

  1. Locate every value entering from outside the type system.
  2. Mark those values as unknown until validation or a trusted boundary establishes their shape.
  3. Choose the simplest guard that matches the runtime reality: typeof, in, instanceof, a predicate, or a discriminant.
  4. Test both the valid and invalid branches of custom guards.
  5. Review affected switches and handlers for newly possible states.
  6. Use the compiler and editor's inferred types to confirm that the narrowing is doing what you intended.

Type narrowing is most effective when it reflects the actual data model. Start with honest uncertainty, prove the facts your code needs, and let the resulting types guide the rest of the implementation.

Related Topics

#typescript#type-narrowing#type-guards#union-types#error-handling
T

TypeScript.page Editorial Team

Technical Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.