When I first started using TypeScript, my go-to type was `any` whenever I wasn’t sure what type to use. It seemed like a catch-all that let me keep moving without friction. But over time, I realized that what I really meant wasn’t “anything goes”; it was “I don’t know what this is… yet.” That’s where `unknown` shines.
The main difference is subtle but impactful: `any` allows you to do anything with the value, bypassing TypeScript’s safety checks, often leading to hidden errors. `unknown`, on the other hand, forces you to validate or refine the type before using it. This nudges you to consciously think through your code, leading to cleaner, more predictable behavior.
Now, whenever I’m uncertain about a type, I default to `unknown`. It’s a powerful reminder that there’s some work left to do in understanding the data flowing through the program. If I genuinely need the flexibility of `any`, I can always switch later—but more often than not, I find that `unknown` was the right choice all along.
Next time you reach for `any`, consider starting with `unknown`. It’s a small shift that could lead to more reliable and maintainable code.
Have you encountered similar scenarios when choosing between ‘unknown’ and ‘any’ in TypeScript? I’d love to hear your thoughts and experiences—let’s learn from each other!
You can check out the full example on my GitHub repo
#TypeScriptTips #CodingBestPractices #TypeSafety #CodeQuality #ProgrammingTips #SoftwareEngineering #DeveloperExperience #TypeScript

Leave a Reply