Sikau

TypeScript · Day 3 · about 20 min

any and unknown

Escape hatches, and the safe one.

When you don't know the type

Data from the internet or a user could be anything. TypeScript has two types for "I don't know": any turns checking off, while unknown keeps you safe by making you check first.

any vs unknown

let a: any = "hello";
a.toFixed(2);

let u: unknown = "hello";
u.toUpperCase();

if (typeof u === "string") {
  console.log(u.toUpperCase());
}

Treat any as a last resort. Reach for unknown and check — your future self will thank you.

The rest of this lesson

  • How any spreadsexplain
  • Checking unknown valuesexplain
  • Which line is an error?predict
  • any or unknown?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript