TypeScript any vs unknown vs never: Choose the Right Type
TypeScriptType SafetyBest Practices

TypeScript any vs unknown vs never: Choose the Right Type

January 21, 2025
9 min read
Salman Izhar

TypeScript: any vs unknown vs never Explained

Understanding these special types is crucial for type-safe TypeScript code.

The any Type

any disables all type checking. Avoid using it in new code.
let value: any;
value = 42;
value = "hello";
value.toUpperCase(); // No error at compile time
When to use: Almost never! Only during JavaScript migration or with untyped third-party libraries.

The unknown Type

unknown is type-safe. You must check the type before using it.
let value: unknown;
value = 42;

// Must check type first
if (typeof value === "string") {
  console.log(value.toUpperCase()); // Safe!
}

Real-World Example:

async function fetchUser(id: string) {
  const response = await fetch(`/api/users/${id}`);
  const data: unknown = await response.json();
  
  if (isUser(data)) {
    return data;
  }
  throw new Error("Invalid data");
}

function isUser(obj: unknown): obj is User {
  return typeof obj === "object" && obj !== null && "id" in obj;
}

The never Type

never represents values that never occur. Used for exhaustive checking.
function throwError(message: string): never {
  throw new Error(message);
}

// Exhaustive check example
type Shape = { kind: "circle" } | { kind: "square" };

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return 0;
    case "square":
      return 0;
    default:
      const _exhaustive: never = shape;
      throw new Error("Unhandled shape");
  }
}

Comparison

| Type | Assign To | Assign From | Use Case | |------|-----------|-------------|----------| | any | Everything | Everything | Migration only | | unknown | any, unknown | Everything | External data | | never | Nothing | Nothing | Impossible states |

Best Practices

1. Never use any in new code 2. Always use unknown for dynamic data 3. Use never for exhaustive type checking 4. Always validate unknown values with type guards

Your code will be safer and more maintainable!

Get More Like This

Want articles like this in your inbox?

Join developers and founders who get practical insights on frontend, SaaS, and building better products.

S

Written by Salman Izhar

Frontend Developer specializing in React, Next.js, and building high-converting web applications.

Learn More