Back to Blog
TypeScriptNeverUnknownTypes

TypeScript never and unknown Types

Master TypeScript never and unknown types for type-safe programming.

B
Bootspring Team
Engineering
October 11, 2018
7 min read

The never and unknown types are essential for type-safe programming in TypeScript. Here's how to use them.

The unknown Type#

Loading code block...

unknown vs any#

Loading code block...

Type Narrowing with unknown#

Loading code block...

The never Type#

Loading code block...

Exhaustive Checks#

Loading code block...

never in Conditional Types#

Loading code block...

unknown in API Responses#

Loading code block...

Error Handling with unknown#

Loading code block...

never as Return Type#

Loading code block...

Type Inference with never and unknown#

Loading code block...

never in Mapped Types#

Loading code block...

Best Practices#

Use unknown When: ✓ Receiving external data (API, user input) ✓ Catch blocks ✓ JSON parsing ✓ Generic value containers Use never When: ✓ Functions that throw or loop forever ✓ Exhaustive type checking ✓ Filtering union types ✓ Impossible code paths Narrowing unknown: ✓ typeof for primitives ✓ instanceof for classes ✓ Type predicates for objects ✓ Assertion functions Avoid: ✗ Using any instead of unknown ✗ Type assertions without validation ✗ Ignoring never in switch defaults ✗ Over-complicating type guards

Conclusion#

unknown is the type-safe alternative to any - use it for values whose type is truly unknown and narrow with type guards. never represents impossible values - use it for exhaustive checks, functions that never return, and filtering types. Together, they enable robust type-safe programming while maintaining flexibility for dynamic values.

Share this article

Help spread the word about Bootspring

Related articles