typescript · level 2 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Some orders have no address. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Address { town: string }
interface Order { item: string; address?: Address }
const orders: Order[] = [
{ item: "lamp", address: { town: "Leeds" } },
{ item: "rug" },
];
for (const order of orders) {
console.log(order.item, order.address?.town ?? "collect in shop");
}
your turn
Your turn. Greet players by their nickname.
Give Olivia a nickname. Then fill in the operator that falls back to the player's name when there is no nickname.
fix it
Guests have no bio, and the checker knows it. Fix it!
- Read the error:
TS18048: 'profile.bio' is possibly 'undefined'.Guests have no bio. - Use
?.to read the length only when there is a bio, and??to fall back to 0. - Change line 3 to
return profile.bio?.length ?? 0;then press run.
nailed it
you can read missing things safely. :D
?.reads a property only when the value is there.- If it is missing,
?.givesundefinedinstead of an error. - Add
??after it to swapundefinedfor a fallback.
new words in your collection
- optional chaining
This lesson isn’t saved. A free account remembers every lesson you finish.