AI Hints
Home›TypeScript Tutorial›Escape Hatches and Nulls
TypeScript · Lesson 10 of 120

any and unknown

The escape hatches.

⏱ 2 min read▶ Video at 8:10🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Sometimes you don't know a value's type, like data from outside your program. TypeScript has two special types for that. Any turns checking off. Unknown keeps it on, and makes you check first.

any and unknown
From the video: any and unknown
  • Type not known
  • any: no checks
  • unknown: check first

any switches checks off

Data has the type any. TypeScript lets us call upper case on it, without complaint. But the value is really a number. Run it. It compiles, then fails while running, exactly what types should prevent.

app.tstypescript
const data: any = 42;

try {
  console.log(data.toUpperCase());
} catch (e) {
  console.log("Crash while running:", (e as Error).message);
}
Output
Crash while running: data.toUpperCase is not a function

unknown makes you check

Now data is unknown. Before using it as a string, we check its type. Inside the if, TypeScript knows it's a string. Run it. The number is handled safely.

app.tstypescript
const data: unknown = 42;

if (typeof data === "string") {
  console.log(data.toUpperCase());
} else {
  console.log("Not text:", data);
}
Output
Not text: 42

Summary

Avoid any. Use unknown, and check the type before using the value. Next, null and undefined.

Key takeaways
  • any: unsafe
  • unknown: safe
  • Check first
Next up: null and undefined — strict checks