×

typescript · level 2 · unit 3 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

reads a property only if there is one.

Checking for undefined with an if works, but it takes three lines every time. Optional chaining does it in two characters: ?.. Write pet.nickname?.toUpperCase() and, if the nickname is missing, the whole thing gives undefined instead of an error.

It pairs well with ??, which you met with prompt. It steps in for undefined as well as null, so pet.nickname ?? pet.name gives the nickname, or the name when there is none.

It works on nested objects too: order.address?.town stops safely at a missing address.

interface Pet {
  name: string;
  nickname?: string;
}
const pets: Pet[] = [{ name: "Rex", nickname: "Rexy" }, { name: "Tom" }];
for (const pet of pets) {
  console.log(pet.nickname?.toUpperCase());
  console.log(pet.nickname ?? pet.name);
}

Use ?. only where a value really might be missing, or it can hide real mistakes.