EasyType System📖 Theory Question

What is the difference between any, unknown, and never in TypeScript?

💡

Hint

any opts out of type checking; unknown is safe any (must narrow); never is the bottom type — unreachable code

Full Answer

These three types occupy opposite ends of the type hierarchy.

any — the escape hatch. Disables all type checking for that value. Assignable to and from everything.

let a: any = 42;
a.foo.bar.baz; // no error — type checking disabled
const b: number = a; // OK — any is assignable to anything

unknown — the type-safe alternative to any. You must narrow it before using it.

let u: unknown = getValueFromAPI();

u.toUpperCase(); // ❌ Error — must narrow first

if (typeof u === 'string') {
  u.toUpperCase(); // ✅ Safe — narrowed to string
}

// unknown is NOT assignable to specific types without narrowing
const s: string = u; // ❌ Error

never — the bottom type. A value that can never exist. Used for:

  • Functions that never return (throw or infinite loop)
  • Exhaustive checks in switch/if statements
  • Impossible intersections
function fail(msg: string): never {
  throw new Error(msg); // never returns
}

// Exhaustive check — never signals unhandled case
type Shape = 'circle' | 'square';
function area(s: Shape) {
  switch (s) {
    case 'circle': return Math.PI;
    case 'square': return 1;
    default:
      const _exhaustive: never = s; // ❌ Error if new case not handled
  }
}
💡 Prefer unknown over any for values from external sources (API responses, JSON.parse). It forces you to validate before use — the TypeScript equivalent of defensive programming.

More Type System Questions

EasyWhat is type inference in TypeScript and when does it kick in?EasyWhat are type assertions and when should you use them?EasyWhat is structural typing (duck typing) in TypeScript?EasyWhat are union types and intersection types? When do you use each?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint