Course contentsShow
← TypeScript
Lesson 926 of 1,79621. The unknown TypeFree lesson

Basic Runtime Type Guard for API Data

Write simple typeof and property checks to narrow unknown JSON to known shapes.

Basic Runtime Type Guard for API Data

You'll learn: How to write simple typeof and property checks to safely narrow unknown JSON payloads into known, usable shapes.


The Core Idea

When you fetch data from an API, TypeScript has no idea what shape that data actually has at runtime. Even if you cast it to a specific type, that's just a compile-time illusion—the actual JavaScript object could be anything.

This is where runtime type guards come in. You write normal JavaScript checks (typeof, in, equality tests) to validate the shape of your data as the program runs. TypeScript watches these checks and narrows the unknown type accordingly, giving you type safety based on actual verification, not wishful thinking.


The Pattern

Start with unknown, then write conditions that check:

  1. Is it an object? (typeof data === 'object' && data !== null)
  2. Does it have the right properties? ('username' in data)
  3. Are those properties the right type? (typeof data.username === 'string')

Each check eliminates possibilities, narrowing unknown down to something specific and usable.


A Simple Example (Conceptual)

Imagine you fetch user data. Instead of blindly assuming it's valid:

  • Check if it's an object (not null, not a primitive)
  • Check if username exists as a property
  • Check if username is a string
  • Only then treat it as a User

TypeScript follows along, understanding that inside your if block, the data is now safe to use.


Why This Matters

It's the bridge between the wild west of runtime JSON and TypeScript's safety. You're teaching TypeScript what the data actually looks like, step by step, using checks that will catch problems when they happen—not in production three weeks later.


Key Takeaway: Runtime type guards use simple JavaScript checks (typeof, in, equality) to narrow unknown API data into known shapes, giving you real type safety based on actual validation, not assumptions.