Lesson 5 / 26
any & unknown
Two ways to opt out of type safety — one dangerous, one safe.
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.