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

null and undefined

Strict checks.

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

Null and undefined mean no value. They cause more crashes than almost anything else. With strict checks on, TypeScript makes you handle them, before they can bite.

null and undefined
From the video: null and undefined
  • No value
  • Common crashes
  • You must handle them

A value that might be missing

Find returns the matching store, or undefined if there's none. So found might be undefined. Run it. TypeScript refuses to let us read its length without checking.

app.tstypescript
const stores = ["Leeds", "York"];
const found = stores.find(s => s.startsWith("H"));
console.log(found.length);
Output
app.ts line 3: 'found' is possibly 'undefined'.

Handling it

We can check with an if. Or use optional chaining, a question mark dot, which gives undefined instead of crashing. Or use two question marks, to give a default value. Run it.

app.tstypescript
const stores = ["Leeds", "York"];
const found = stores.find(s => s.startsWith("H"));

if (found) console.log(found.length);
console.log(found?.length);
console.log(found ?? "no store found");
Output
undefined
no store found

Summary

Strict checks make you handle missing values, with if, optional chaining, or a default. Next, the basics quiz.

Key takeaways
  • if (x)
  • x?.y
  • x ?? default
Next up: Basics Quiz — test yourself