TypeScript
/Intermediate
any vs unknown vs never
Definition
Special types in TypeScript. `any` turns off type checking. `unknown` is a safer `any` that forces you to check the type before using it. `never` represents a state that should never logically occur.
Explain Like I'm New
`any` is turning off the smoke alarm. `unknown` is a suspicious package; you can hold it, but you aren't allowed to open it until you scan it. `never` is an empty black hole; a function that returns `never` means it crashed or runs infinitely.
Real World Example
Using `unknown` for data coming from a 3rd-party API `const data: unknown = fetch(...)`, forcing you to write `if (typeof data === 'string')` before accessing it.
Common Use Cases
- •Handling dynamic API data (unknown)
- •Exhaustiveness checking in switch statements (never)
- •Escaping the type system entirely (any - rarely recommended)
Interactive Example
Loading Code Playground...
Interview Questions
basic
- Why is using `any` considered bad practice?
intermediate
- Why is `unknown` safer than `any`?
advanced
- How do you use `never` for exhaustive `switch` checks?