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

Destructured Parameters with Defaults

Using default values in object destructuring parameters and how types flow through the pattern.

Destructured Parameters with Defaults

You'll learn how to combine object destructuring in function parameters with default values and how TypeScript infers types through this pattern.

The Core Idea

Just as you can use default values with regular parameters, you can assign defaults to destructured properties within function parameters. TypeScript cleverly infers types from these defaults, allowing you to write cleaner, more expressive function signatures without explicit type annotations.

How It Works

When you destructure an object parameter and provide defaults, TypeScript automatically understands the types:

function greet({ name = "Guest", age = 0 }) {
  console.log(`${name} is ${age} years old`);
}

greet({ name: "Alice", age: 30 }); // Alice is 30 years old
greet({ name: "Bob" }); // Bob is 0 years old
greet({}); // Guest is 0 years old

Here, TypeScript infers that name is a string and age is a number based on the default values.

Combining with Type Annotations

You can also explicitly type the entire parameter object:

function configure({ debug = false, timeout = 5000 }: { debug?: boolean; timeout?: number }) {
  // TypeScript knows debug is boolean, timeout is number
}

The defaults make the properties optional in the type annotation (notice the ?), but provide fallback values when omitted.

Think of It Like a Menu

Imagine ordering from a restaurant menu with "house defaults." You can customize specific items or accept the chef's recommendations—the restaurant knows what each item is regardless of whether you customize it.

Key Takeaway: Destructured parameters can have default values, and TypeScript infers their types from those defaults, making your function signatures both flexible and type-safe.