BeginnerCoder

Lesson 7 — Interfaces: adding fields

Optional fields

Some fields are not always there — not every user gives an email. Put ? after the name (email?: string) to make a field optional: objects may leave it out, and TypeScript reminds you that reading it can give undefined.

interface Pet { name: string; nickname?: string }
const p: Pet = { name: "Rex" };           // ok without nickname
console.log(p.nickname ?? "no nickname");

Why it matters: it describes real forms and API data where some values are missing, and forces you to handle that case.

Want it another way?
Task

Add an optional email to User and give Sam the email sam@example.com. Ann has none.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.