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

Default Parameter Values

Assigning default values to parameters and how TypeScript infers their types from the defaults.

Default Parameter Values

You'll learn: How to assign fallback values to function parameters and how TypeScript automatically infers types from those defaults.

What Are Default Parameter Values?

In JavaScript and TypeScript, you can specify a default value for a function parameter. If the caller doesn't provide that argument (or passes undefined), the default kicks in automatically. This makes parameters effectively optional without requiring the ? syntax.

The Syntax

function greet(name: string, greeting: string = "Hello") {
  return `${greeting}, ${name}!`;
}

greet("Alice");           // "Hello, Alice!"
greet("Bob", "Hi");       // "Hi, Bob!"
greet("Charlie", undefined); // "Hello, Charlie!"

Notice you didn't need to write greeting?: string. The default value "Hello" makes greeting optional and tells TypeScript its type is string.

TypeScript Infers the Type from the Default

TypeScript looks at your default value and infers the parameter's type automatically:

function multiply(a: number, b = 2) {
  return a * b;
}
// TypeScript knows b is a number because 2 is a number

You can still add an explicit type annotation, but it's usually unnecessary:

function multiply(a: number, b: number = 2) {
  return a * b;
}

Both versions behave identically. The first is more concise; the second is more explicit.

Why This Matters

Default parameters let you write cleaner function calls without cluttering your code with if (param === undefined) checks. TypeScript ensures the default value matches the parameter's usage, catching mismatches at compile time.

Key Takeaway: Default parameter values make parameters optional and allow TypeScript to infer their types automatically from the assigned value, reducing the need for explicit annotations.