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

Why unknown Is Ideal for Network Data

Network responses have no compile-time guarantees; unknown forces validation before use.

Why unknown Is Ideal for Network Data

You'll learn: Why TypeScript's unknown type is the safest choice when handling data from APIs, servers, or any external source.


When you fetch data from a network request—whether it's an HTTP API, a WebSocket message, or a file read from disk—TypeScript has zero compile-time knowledge of what that data actually contains. The server could send valid JSON, malformed data, unexpected structures, or change its response format without warning.

This is where unknown becomes essential.

The Network Data Problem

Think of network data like a package delivered to your door. You can see there's something inside, but you don't know if it's what you ordered, if it's damaged, or if someone sent you something completely different. You wouldn't just assume it's safe to use—you'd open it and check first.

Using any for network data is like blindly trusting the package and immediately using whatever's inside. TypeScript won't stop you from accessing properties that don't exist or calling methods on undefined values. Runtime errors are guaranteed eventually.

Using unknown forces you to validate first, use second. It represents "I know data exists, but I must verify its shape before using it."

Practical Pattern: API Response Handling

async function fetchUser(id: number): Promise<unknown> {
  const response = await fetch(`/api/users/${id}`);
  const data = await response.json();
  return data; // unknown forces validation downstream
}

// Now you MUST check before using
const userData = await fetchUser(123);

// ❌ Error: Can't access property on unknown
// console.log(userData.name);

// ✅ Validate structure first
if (
  typeof userData === 'object' &&
  userData !== null &&
  'name' in userData &&
  typeof userData.name === 'string'
) {
  console.log(userData.name); // Safe!
}

Key Takeaway: Network responses have no compile-time guarantees; unknown forces validation before use, preventing runtime explosions from unexpected data shapes.