typescript · level 2 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A missing phone number. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Contact {
name: string;
phone?: string;
}
const friends: Contact[] = [{ name: "Ada", phone: "0123" }, { name: "Raj" }];
for (const friend of friends) {
console.log(friend.name, friend.phone);
}
your turn
Your turn. Add an optional middle name.
Make middle optional in the interface. Then fill in one person with a middle name and one without.
fix it
Not every film has a sequel. Fix it!
- Read the error:
TS18048: 'film.sequel' is possibly 'undefined'.Some films have no sequel. - Before line 3 uses it, check whether
film.sequelisundefined, and return a message if it is. - Add
if (film.sequel === undefined) { return "No sequel yet"; }before line 3, then press run.
nailed it
your shapes can have gaps now. :D
- A
?after a property name makes it optional. - A missing optional property reads as
undefined. - Check for
undefinedbefore you use it.
new words in your collection
- optional property
This lesson isn’t saved. A free account remembers every lesson you finish.