×

typescript · level 2 · unit 3 · lesson 1

  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

An might be there, or might not.

Not every pet has a nickname. Put ? after a property's name, like nickname?: string, and objects may leave it out without the checker complaining.

The catch: reading it gives string | undefined, because it might be missing. Use it as if it were always there, like pet.nickname.toUpperCase(), and the checker says TS18048: possibly undefined.

When you show a whole object, a missing optional property is not shown at all.

interface Pet {
  name: string;
  nickname?: string;
}
const rex: Pet = { name: "Rex", nickname: "Rexy" };
const tom: Pet = { name: "Tom" };
console.log(rex.nickname);
console.log(tom.nickname);
console.log(tom);

Read the ? as “maybe”: maybe there is a nickname, maybe not.