Course contentsShow
← TypeScript
Lesson 259 of 1,7966. FunctionsFree lesson

Common Patterns: Config Objects

Using optional and default parameters effectively in configuration object patterns for APIs.

Common Patterns: Config Objects

You'll learn how to combine optional parameters and defaults to create flexible, user-friendly configuration objects in TypeScript functions.

The Core Idea

Configuration objects are parameters that bundle many related options into a single object, making function calls cleaner and more maintainable. By combining optional properties and default values, you let users specify only what they care about while providing sensible fallbacks for everything else.

Think of ordering a custom sandwich: you specify the bread, filling, and extras you want, but the shop has defaults for everything you don't mention (mayo instead of mustard, toasted instead of cold). You don't need to state every single detail.

The Pattern in Action

function createServer(config: {
  port?: number;
  host?: string;
  ssl?: boolean;
}) {
  const port = config.port ?? 3000;
  const host = config.host ?? 'localhost';
  const ssl = config.ssl ?? false;
  
  console.log(`Server at ${host}:${port}, SSL: ${ssl}`);
}

// Minimal usage
createServer({});

// Partial configuration
createServer({ port: 8080 });

// Full configuration
createServer({ port: 443, host: 'example.com', ssl: true });

All properties are optional (?), so TypeScript allows empty objects or partial configurations. Inside the function, you provide defaults using the nullish coalescing operator or destructuring defaults.

This pattern appears everywhere: API clients, UI component props, build tool configurations, and database connections all use this approach to balance flexibility with simplicity.

Key Takeaway: Configuration objects with optional properties and default values create flexible APIs that are both beginner-friendly (minimal required setup) and powerful (full customization when needed).