Lesson

TypeScript Type Guards

10 min reading
Free Course

TypeScript Type Guards: Narrowing unknown and Unions Safely

A type guard is a runtime check that proves to TypeScript a variable belongs to a narrower type inside a conditional branch. Because TypeScript strips types during compilation, type guards run real JavaScript checks (typeof, instanceof, in) that keep both compile time and runtime safe.

When built-in operators are not enough—such as validating a plain JSON object—you write a user-defined type predicate returning value is TargetType.

Built-In Guards vs. Custom Type Predicates

flowchart TD
    A["input: unknown"] -->|"typeof === 'string'"| B["Narrowed: string"]
    A -->|"'id' in input"| C["Has property 'id'"]
    A -->|"isApiError(input)"| D["Custom predicate: ApiError"]

Write a custom predicate function when you want reusable validation logic across multiple handlers:

interface ApiError {
  code: number;
  message: string;
}

function isApiError(value: unknown): value is ApiError {
  return (
    typeof value === "object" &&
    value !== null &&
    "code" in value &&
    typeof (value as ApiError).code === "number" &&
    "message" in value &&
    typeof (value as ApiError).message === "string"
  );
}

function handleFailure(err: unknown): string {
  if (isApiError(err)) {
    return `Error ${err.code}: ${err.message}`;
  }
  if (err instanceof Error) {
    return err.message;
  }
  return "Unexpected error";
}

console.log(handleFailure({ code: 404, message: "Lesson missing" }));

Assertion Functions (asserts value is T)

Instead of returning a boolean, function assertNonNull<T>(val: T): asserts val is NonNullable<T> throws an error if invalid, narrowing val for all remaining lines below the call.

Common Mistakes to Avoid

  • Writing dishonest type predicates: TypeScript trusts val is User blindly—if your check just writes return true, bad runtime data bypasses all type safety.
  • Using typeof x === "object" without x !== null: In JavaScript, typeof null returns "object", so always pair it with x !== null.
  • Checking instanceof on plain JSON objects: JSON.parse() produces plain objects, not class instances, so data instanceof User always returns false.

Frequently Asked Questions

What changed for array .filter() in TypeScript 5.5?

In TypeScript 5.5+, simple checks like items.filter((x) => x !== undefined) automatically infer a type predicate without manually writing (x): x is Item => ....

Can in narrow union types?

Yes. If type Shape = Circle | Square where only Circle has radius, if ("radius" in shape) narrows shape cleanly to Circle.

When should I reach for Zod instead of manual type predicates?

For large nested API payloads with dozens of fields, schema validators like Zod or Valibot eliminate error-prone hand-written typeof checks.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum