Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 5 of 9

`any`, `unknown`, and `never` - The Special Types

`any`, `unknown`, and `never` are TypeScript's escape hatches and boundary markers. `any` disables the type system entirely. `unknown` is the safe alternative - it forces you to narrow before using a value. `never` represents something that should never happen and is the foundation of exhaustiveness checking.

13 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

any vs unknown vs never - Deep Comparison

any vs unknown vs never - Deep Comparison
// ── any - complete type system exit ─────────────────────────
// Use ONLY when typing legacy JS with no @types available
let value: any = "hello";
value = 42;                // ✅ no error
value.foo.bar.baz;         // ✅ no error - but crashes at runtime!
value();                   // ✅ no error - but crashes at runtime!
// any is contagious: anything it touches becomes any

// ── unknown - the safe alternative to any ────────────────────
let safeValue: unknown = fetchFromUnknownApi();
safeValue.toUpperCase(); // ❌ Error: Object is of type 'unknown'.
                          // You MUST narrow before using unknown.

if (typeof safeValue === "string") {
  safeValue.toUpperCase(); // ✅ narrowed to string
}

// ── When to use unknown vs any ────────────────────────────────
// API boundaries where you don't control the data:
async function getApiData(): Promise<unknown> {
  const res = await fetch("/api/data");
  return res.json();          // json() returns any - wrap in unknown
}

// catch blocks - always use unknown (TypeScript 4+ default in strict):
try {
  JSON.parse("bad json");
} catch (error: unknown) {       // ✅ unknown is safer than Error
  if (error instanceof Error) {
    console.error(error.message); // ✅ safely accessed
  }
}

// ── never - the impossible type ───────────────────────────────
// A value of type never can never exist.
// Functions that NEVER return are typed as never:
function fail(message: string): never {
  throw new Error(message);  // this function never completes normally
}

// ── never for exhaustiveness checking ────────────────────────
// The MOST important use of never in production code:
type Status = "draft" | "published" | "archived";

function handleStatus(status: Status): string {
  switch (status) {
    case "draft":     return "📝 Draft";
    case "published": return "✅ Published";
    case "archived":  return "🗄️ Archived";
    default:
      // If you add a new Status and forget to handle it here,
      // TypeScript raises a compile error on this line:
      const exhausted: never = status;
      throw new Error(`Unhandled status: ${exhausted}`);
  }
}
// Now add "deleted" to Status → instant compile error at default.
// This is how TypeScript enforces complete switch coverage.

Common Mistakes

  • Using `any` in catch blocks - pre-TypeScript 4, catch bound `error` as `any`. Always annotate as `unknown` and narrow. `error instanceof Error` is the standard check.
  • Returning `never` from functions that return `undefined` - `never` means the function cannot complete (throws or loops forever). A function returning nothing is `void`, not `never`.
  • Ignoring the exhaustiveness pattern - adding values to a union type should immediately surface everywhere that union is switched on. Without `never` in the default branch, new cases are silently ignored.

Tip

Tip

Practice any vs unknown vs never Deep Comparison in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for `any`, `unknown`, and `never` - The Special Types

Practice Task

Note

Practice Task - (1) Write a working example of any vs unknown vs never Deep Comparison from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with any vs unknown vs never Deep Comparison is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • `any`, `unknown`, and `never` are TypeScript's escape hatches and boundary markers.
  • Using `any` in catch blocks - pre-TypeScript 4, catch bound `error` as `any`. Always annotate as `unknown` and narrow. `error instanceof Error` is the standard check.
  • Returning `never` from functions that return `undefined` - `never` means the function cannot complete (throws or loops forever). A function returning nothing is `void`, not `never`.
  • Ignoring the exhaustiveness pattern - adding values to a union type should immediately surface everywhere that union is switched on. Without `never` in the default branch, new cases are silently ignored.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done