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

Optional Properties in Function Parameters

Use optional properties in object parameters to create flexible function signatures.

Optional Properties in Function Parameters

You'll learn: How to use optional properties inside function parameter objects to create flexible, self-documenting function signatures.

The Core Idea

When a function accepts an object as a parameter, you can mark some of that object's properties as optional using ?. This tells TypeScript (and your teammates) which configuration values are required and which have sensible defaults or can be omitted entirely.

Think of it like ordering a custom sandwich: the bread and main filling are required parameters, but extras like "add cheese?" or "toasted?" are optional properties you can specify or skip.

Why This Matters

Instead of creating multiple function overloads or long parameter lists, you can define a single object parameter with a mix of required and optional properties. This makes your function calls cleaner and more readable.

Basic Syntax

function createUser(config: { name: string; age?: number }) {
  console.log(`Name: ${config.name}`);
  if (config.age !== undefined) {
    console.log(`Age: ${config.age}`);
  }
}

createUser({ name: "Alice" }); // age is optional, so this works
createUser({ name: "Bob", age: 30 }); // providing age also works

Real-World Pattern

function fetchData(options: { url: string; timeout?: number; retries?: number }) {
  const actualTimeout = options.timeout ?? 5000;
  const actualRetries = options.retries ?? 3;
  // Use url (required), timeout and retries (optional with defaults)
}

fetchData({ url: "/api/data" });
fetchData({ url: "/api/data", timeout: 10000 });

Key Takeaway: Optional properties in object parameters let you build flexible function interfaces where callers only specify what they need, while TypeScript enforces that required values are always provided.