Optional Properties in Interfaces
What you'll learn: How to mark interface properties as optional using the ? syntax, making them flexible without losing type safety.
The Core Concept
When defining an interface, you often want to allow certain properties to be present or absent. TypeScript lets you mark properties as optional by adding a ? after the property name. This tells the compiler: "This property might be there, or it might not—both are valid."
Why Optional Properties Matter
Think of an interface like a form. Some fields are required (name, email), while others are optional (phone number, middle name). Optional properties in interfaces work the same way—they describe what can be there without demanding it must be there.
Syntax and Usage
interface User {
id: number;
name: string;
email?: string; // Optional property
phone?: string; // Optional property
}
const user1: User = {
id: 1,
name: "Alice"
// email and phone can be omitted
};
const user2: User = {
id: 2,
name: "Bob",
email: "bob@example.com"
// phone still optional
};
Both user1 and user2 are valid because email and phone are marked as optional. TypeScript won't complain about their absence.
The Type Safety Guarantee
When you access an optional property, TypeScript treats its type as a union with undefined:
function greet(user: User) {
// user.email has type: string | undefined
console.log(user.email.toLowerCase()); // Error! email might be undefined
}
This forces you to handle the "might not exist" case safely.
Key Takeaway: Use ? after a property name in interfaces to make that property optional—it can be present or absent, and TypeScript will track that uncertainty for you.