Lesson

TypeScript Special Types

10 min reading
Free Course

TypeScript Special Types: unknown, any, void, and never

TypeScript adds four special types that JavaScript lacks: any, unknown, void, and never. Choosing unknown over any and using never for exhaustive checks prevents silent runtime crashes across large apps.

Think of unknown as the type-safe counterpart to any: both accept any value, but unknown forces you to verify the value's type before touching its properties.

Comparing Special Types Side by Side

Type Accepts Any Value? Requires Narrowing Before Use? Primary Purpose
any Yes No (disables checking!) Last-resort escape hatch
unknown Yes Yes (typeof, instanceof) Safe untrusted input (JSON.parse)
void undefined only N/A Functions with no return value
never Nothing N/A Throwing functions & exhaustive checks

Using unknown and never in Practice

function parseMessage(raw: unknown): string {
  if (typeof raw === "string") {
    return raw.trim();
  }
  if (raw instanceof Error) {
    return raw.message;
  }
  return "Unknown payload";
}

function fail(reason: string): never {
  throw new Error(reason);
}

console.log(parseMessage("  ready  "));

Exhaustive Checking with never

Assigning an unhandled union branch to const check: never = status makes the compiler fail immediately whenever a teammate adds a new union option and forgets to handle it.

Common Mistakes to Avoid

  • Defaulting to any whenever a type error feels annoying: Every any turns off type checking for everything that touches it downstream.
  • Confusing void with never: A void function returns normally without a meaningful value; a never function never finishes (it always throws or loops forever).
  • Forgetting useUnknownInCatchVariables: Modern strict mode types catch (err) as unknown instead of any, protecting you from reading err.message on non-Error throws.

Frequently Asked Questions

When is any actually acceptable?

Temporary migration of legacy JavaScript files or low-level generic wrappers where unknown cannot express the constraint.

Can a void function still execute return;?

Yes. return; (with no value) or reaching the end of the function body is valid for void.

Why does an empty array sometimes infer as never[]?

Under strictNullChecks, const list = [] with no type annotation can infer never[] if never pushed to, blocking future .push("a") calls unless typed as string[].

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum