Lesson 5 / 28
any & unknown
Compare any and unknown, and learn why unknown with narrowing is the safer choice for API and JSON data.
any: the escape hatch
any turns off type checking for that value completely. It compiles, but you've thrown away TypeScript's whole point.
unknown: the safer any
unknown accepts anything too, but you must narrow it before using it — TS forces a check first.
let data: unknown = JSON.parse('"hello"');
data.toUpperCase();
// Error: 'data' is of type 'unknown'.
if (typeof data === "string") {
data.toUpperCase(); // OK, narrowed to string
}Prefer unknown over any
For truly unpredictable data (API responses, JSON), reach for unknown and narrow it — keep any only as a last resort.