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

unknown for Deserialization Functions

Functions like JSON.parse should return unknown, forcing callers to validate before assuming structure.

unknown for Deserialization Functions

What you'll learn: Why functions that parse or deserialize external data should return unknown instead of any, forcing safe validation at every call site.

The Core Idea

Deserialization functions convert external data (strings, bytes, network responses) into JavaScript objects. The problem: You have no compile-time guarantee about what that data actually contains.

Functions like JSON.parse() should return unknown (and in modern TypeScript, they do when strictNullChecks is on). This forces you to validate the shape before assuming it's safe to use. Without this, you'd have a typed function returning an unchecked value, creating a dangerous type-safety gap.

Why This Matters

Imagine JSON.parse returned any:

const data = JSON.parse(apiResponse); // type: any
console.log(data.user.email.toUpperCase()); // compiles, crashes at runtime

No error until runtime—TypeScript can't help you.

If it returns unknown:

const data = JSON.parse(apiResponse); // type: unknown
console.log(data.user.email.toUpperCase()); 
// ❌ Error: Object is of type 'unknown'

Now you must validate before use—exactly what you need for untrusted data.

The Pattern

When you write deserialization helpers, make them return unknown:

function parseConfig(jsonString: string): unknown {
  return JSON.parse(jsonString);
}

function loadUserData(response: string): unknown {
  return JSON.parse(response);
}

Callers are forced to narrow with type guards:

const rawConfig = parseConfig(input);

if (typeof rawConfig === 'object' && rawConfig !== null) {
  // now you can safely check properties
}

This design makes the unsafe boundary explicit: deserialization creates unknown, and validation narrows it to a known type.

Key Takeaway: Deserialization functions should return unknown, not any, to enforce type validation at the boundary between external data and your typed codebase.