Course contentsShow
← TypeScript
Lesson 129 of 1,7963. Basic TypesFree lesson

Introduction to unknown: The Type-Safe any

Understand unknown as a top type that requires narrowing before use, unlike any.

Introduction to unknown: The Type-Safe any

What you'll learn: How unknown provides a safer alternative to any by forcing you to verify types before use.


The Core Idea

While any completely disables type checking, unknown says "I don't know what this is yet, but you must figure it out before you use it." It's TypeScript's way of representing values whose type is truly uncertain without abandoning type safety.

Think of any like an unlocked door—anyone can walk through without checking. unknown is a locked door where you must verify who's knocking before letting them in.

How unknown Works

When you declare something as unknown, TypeScript won't let you do anything with it until you narrow down what it actually is:

let mysteryBox: unknown;

mysteryBox = 42;
mysteryBox = "hello";
mysteryBox = true; // All assignments work

// But you can't USE it without checking first:
// let result = mysteryBox.toUpperCase(); // ❌ Error!

You must verify the type first:

if (typeof mysteryBox === "string") {
  let result = mysteryBox.toUpperCase(); // ✅ Now it's safe
}

unknown vs any

  • any: "Do whatever you want, I give up on type safety"
  • unknown: "I don't know yet, but prove it to me before using it"

When working with unpredictable inputs (user data, API responses), unknown forces you to handle all possibilities safely.

Key Takeaway: unknown is a top type that requires type narrowing before use—it's the safe way to represent truly uncertain values without losing TypeScript's protection like any does.