The never and unknown types are essential for type-safe programming in TypeScript. Here's how to use them.
The unknown Type#
unknown vs any#
Type Narrowing with unknown#
The never Type#
Exhaustive Checks#
never in Conditional Types#
unknown in API Responses#
Error Handling with unknown#
never as Return Type#
Type Inference with never and unknown#
never in Mapped Types#
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.