Sikau

TypeScript · Day 12 · about 25 min

Null safety

Strict null checks, ?. and !.

The billion-dollar mistake

"Cannot read properties of undefined" is the most common JavaScript crash. In strict mode, TypeScript tracks where a value might be missing and won't let you use it until you've handled that.

Possibly missing values

const users = [{ name: "Asha", city: "Pokhara" }];
const found = users.find((u) => u.name === "Ram");
console.log(found.city);

console.log(found?.city ?? "Unknown");
if (found) console.log(found.city);

const el = document.querySelector("#title");
el.textContent = "Hi";

The rest of this lesson

  • Where missing values come fromexplain
  • Choosing how to handle itexplain
  • Error or not?predict
  • ?. and ??predict
  • 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