
Mastering unknown vs never Types in TypeScript: Differences and Use Cases
unknown Type Represents any value, but is safer than any —you cannot use its value directly without type-checking or type assertion Use when you want to accept any type but enforce type-safety downstream Example: function logValue ( value : unknown ) { if ( typeof value === " string " ) { console . log ( value . toUpperCase ()); } } Key Points: Forces you to perform a type check before using the value Useful in libraries for handling user input, JSON parsing, etc. never Type Represents values that never occur Used as the return type for functions that never return (e.g., throw exceptions or have infinite loops) Example: function fail ( message : string ): never { throw new Error ( message ); } Key Points: Helpful for exhaustive checks (e.g., switch statements) Informs TypeScript that code after a never function is unreachable When to Use Which? Use unknown for any value you want type-checked later Use never for impossible states or functions never meant to return
Continue reading on Dev.to
Opens in a new tab




