What Is the Difference Between any
and unknown
in TypeScript?
Understanding the subtle distinction to type like a mapache!
Let’s face it: even the most seasoned of TypeScript developers sometimes trip up over TypeScript’s complex type system. After all, as the language matures and expands, the distinctions can become increasingly nuanced. One of the more subtle distinctions is between the any
and unknown
types.
Fear not! With the guidance of our friendly mapache 🦝, we’ll unravel the unknown
mystery of these perplexing types! You won’t have any
problems.
The Wild West of any
Types in TypeScript
Picture a wild mapache 🦝 running rampant in your codebase — that’s essentially the any
type. Yeehaw, mapache! Woah boy, whoa!
The any
type allows you to assign values of any type to it, without TypeScript ever yelling at you, no matter what you do to that poor type:
let freeMapache: any = "I am a string now!"
freeMapache = 12345 // Now I am a number!
freeMapache = {name: "Rocky"} // And now an object!
// Since we're using `any`, you'll never see a TypeScript type error!
You can try this code example yourself over in the TypeScript Playground.