Beginner · 10 min
Optional and nullable values
Check missing values instead of assuming that they exist.
Read an optional property
A question mark marks an optional property. Reading it may produce undefined. Optional chaining skips the access when the value is missing.
type User = { name: string; nickname?: string };
const user: User = { name: "Ada" };
console.log(user.nickname?.toUpperCase() ?? user.name);Output
Ada
Handle null explicitly
With strictNullChecks, null is not automatically allowed wherever a string is expected. Include it in the type when it is a real possibility, then handle it.
function displayName(name: string | null): string {
return name ?? "Guest";
}
console.log(displayName(null));Output
Guest
Put it into practice
- Read the types and predict the output before running the examples.
- Complete the task, then check your understanding with the practice questions.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Handle a missing nickname
Display "Guest" when "nickname" is absent. Otherwise display the uppercase nickname.
Combine optional chaining with a fallback using ??.