Course contentsShow
← TypeScript
Lesson 300 of 1,7967. ObjectsFree lesson

Optional Properties with ?

Mark object properties as optional using the ? modifier to allow them to be omitted.

Optional Properties with ?

You'll learn how to mark object properties as optional so that they can be safely omitted when creating objects.

What Are Optional Properties?

In real-world objects, not every property always makes sense. A user profile might have an optional bio, or a product might have an optional discount. TypeScript lets you express this with the ? modifier.

When you add ? after a property name in an object type, you're telling TypeScript: "This property might exist, or it might not—both are valid."

The Syntax

type User = {
  name: string;
  age: number;
  bio?: string;  // This property is optional
};

The bio? means bio can either be a string or undefined—or simply absent from the object entirely.

Using Optional Properties

type Product = {
  id: number;
  name: string;
  discount?: number;
};

const laptop: Product = {
  id: 1,
  name: "ThinkPad"
  // discount is omitted — totally fine!
};

const phone: Product = {
  id: 2,
  name: "iPhone",
  discount: 10  // Also fine to include it
};

Notice you can create valid Product objects with or without the discount property.

Think of It Like This

Imagine a form where some fields are marked "optional." You can submit it whether you fill them out or not. The ? modifier works the same way—it tells TypeScript: "Don't complain if this field is missing."

Without ?, TypeScript requires every property to be present. With ?, you get flexibility without losing type safety.

Key Takeaway: Use the ? modifier after a property name to make it optional, allowing objects to omit that property without causing type errors.