Ad space (banner)
Lesson 17 / 20

The any and unknown Types

This lesson covers the difference between any and unknown, both used for handling a value whose type isn't known. It's for anyone searching "TypeScript any unknown difference."

The any type "accepts any type at all, effectively turning off TypeScript's type checking." The unknown type also accepts any value, but it's the safer option โ€” it forces you to check the actual type before you can use it, or you get an error.

The example receives a value assumed to come from an external source as unknown, checks whether it's a string with typeof, and only then calls .toUpperCase().

A common early mistake is reaching for any too casually with the reasoning "I don't know the type, so I'll just make it any for now." Overusing any strips away the type checking that's the whole benefit of using TypeScript in the first place. When in doubt, reach for unknown and narrow the type only as much as you actually need โ€” it's the safer default.

In real projects, receiving data whose type isn't confirmed until runtime โ€” like an external API's response, or the result of JSON.parse โ€” as unknown, then validating it before use, is the recommended pattern.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)