Lesson 5 +10 XP

Special Types: any, unknown & never

Special Types: any, unknown, and never

TypeScript includes special escape hatch and type-safety types to handle dynamic data or impossible control flows.

Summary of Special Types

TypeSafety LevelUsage
anyUnsafeOpts out of all type checking. Avoid in production.
unknownType-safeTop type for values of uncertain type. Requires type narrowing before use.
neverBottom typeRepresents values that NEVER occur (e.g. functions throwing errors or infinite loops).

Comparison Code Examples

Using any (DANGEROUS):

let data: any = "hello";
data.nonExistentMethod(); // Compiles fine, crashes at runtime!

Using unknown (SAFE):

let value: unknown = "hello";
// value.toUpperCase(); // Error: Object is of type 'unknown'.

if (typeof value === "string") {
  console.log(value.toUpperCase()); // Safe! Type narrowed to string.
}

Using never (Exhaustiveness checking):

function throwError(msg: string): never {
  throw new Error(msg);
}

TL;DR

  • Prefer unknown over any when dealing with external API responses or dynamic inputs.
  • unknown forces you to perform type checking/narrowing before calling methods on it.
  • never ensures exhaustive switch statements and represents impossible values.