Optional Properties
👨💼 Not every user fills out all their profile fields. We need to handle
optional data gracefully.
Use
? to mark a property as optional:const user: { name: string; bio?: string } = {
name: 'Alice',
// bio is optional, so we can omit it
}
- Create a
UserProfileobject type with required and optional properties - Create users with and without the optional properties
- Safely access optional properties (check before using!)
💰 Safely accessing optional properties:
if (user.bio !== undefined) {
console.log(user.bio.toUpperCase()) // Safe!
}
// Or use optional chaining:
console.log(user.bio?.toUpperCase()) // Returns undefined if bio is undefined