- 01Getting Started
- 02Your First Output (console.log)
- 03Variables and Type Annotations (number/string/boolean)
- 04Array Types
- 05Function Types (Parameters and Return Values)
- 06Optional Parameters and Default Parameters
- 07Interfaces (interface)
- 08Optional Properties (?)
- 09Type Aliases (type)
- 10Union Types
- 11Literal Types
- 12enum (Enumerated Types)
- 13Classes and Types
- 14Inheritance (extends) and Implementing an Interface (implements)
- 15Generics (<T>)
- 16Tuple Types
- 17The any and unknown Types
- 18Type Assertions (as)
- 19The readonly Modifier
- 20[Applied] Build a Mini Inventory Management System
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.
๐งช 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).
