QuestionsTypeScript

unknown vs any vs never

Top & Bottom TypesEasyTypeScript

Explain the difference between unknown, any, and never, and when to use each.

What it tests

Whether you understand the type lattice and use unknown to keep type-safety at boundaries.

Approach & answer

any opts out of the type system entirely — every operation is allowed and errors slip through silently; it should be a last resort. unknown is the type-safe top type: any value is assignable TO unknown, but you can do nothing WITH an unknown until you narrow it (typeof/instanceof/a type guard). That makes unknown the correct type for anything crossing a trust boundary — JSON.parse results, external API payloads, catch clause errors — because it forces validation before use. never is the bottom type: it has no values and is assignable to every type but nothing is assignable to it. It surfaces for a function that never returns (throws or infinite-loops), for the impossible branch after an exhaustive switch, and for empty intersections. The exhaustiveness pattern — assigning the switch's default value to a never-typed variable — turns a missed union case into a compile error, which is one of TypeScript's highest-leverage safety idioms.

Use this technique when

Typing catch errors and parsed JSON (unknown); enforcing exhaustive switches (never); avoid any except in genuine escape hatches.

References

ts