100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
TypeScript Deep Dive
30 minintermediate

Working with unknown, never and Assertion Functions

Three special types and one special function form sit at the edges of the type system and are essential for handling values safely at boundaries: `unknown`, the safe top type that can hold anything but lets you do nothing until you check it; `never`, the bottom type that represents the impossible and the unreachable; and assertion functions, which narrow a value by throwing if it does not match, teaching the compiler something it cannot otherwise verify. This matters because the riskiest code in any application lives at its boundaries — JSON from the network, user input, third-party data, dynamic values — where you receive things whose type you cannot trust. Reaching for `any` there throws away all safety; `unknown` keeps you honest by forcing a check first. `never` powers exhaustiveness and models functions that do not return, and assertion functions let validation results flow into the type system. Together they are the tools for crossing the line between the untyped outside world and your typed code without surrendering safety, which is exactly where many real bugs originate.

Analogy🏏Cricket
🏏 Think of it like cricket: Picture how a scoreboard operator constructs every display string from fixed components in a strict format — a batter's line is always built as `${name} ${runs} (${balls})`, never improvised. The format is a template with slots, and only values that fit each slot are allowed. Just as the scoreboard builds each line by filling a fixed template with the right pieces, a template literal type builds a string type by filling a pattern with other types. Just as a stray entry that does not match the format — text where runs should go — is rejected by the operator, a string that does not match the template literal type is rejected by the compiler. Just as the format guarantees every line is readable and consistent, the template type guarantees every string matches the intended shape. This reveals why template literal types matter: strings in software follow patterns just like scoreboard lines, and encoding the pattern into the type makes every malformed string an immediate error.
Lesson 23 of 35
0% complete