How Do Optional and Default Parameters Work in TypeScript?

Learn How Do Optional and Default Parameters Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Optional and Default Parameters

Function parameters allow developers to pass information into a function. In many applications, some arguments are required while others are optional. For example, a greeting function may require a name but allow the caller to provide a custom greeting. A price calculation function may require an amount while using a default tax rate when no rate is supplied.

TypeScript supports optional parameters and default parameters to handle these situations. Optional parameters let callers omit an argument, while default parameters provide a fallback value when an argument is omitted or explicitly passed as undefined.

Understanding the difference between these features helps you design flexible function signatures without weakening type safety. These techniques are useful in reusable utilities, API services, configuration functions, event handlers, and application business logic.

1. What Are Optional Parameters?

An optional parameter is an argument that a caller does not have to provide. In TypeScript, add a question mark (?) after the parameter name to make it optional.

function greetUser(
  name: string,
  greeting?: string
): string {
  if (greeting === undefined) {
    return "Hello, " + name + "!";
  }

  return greeting + ", " + name + "!";
}

console.log(greetUser("Asha"));
console.log(greetUser("Ravi", "Welcome"));

The name parameter is required, while greeting is optional. The caller can provide either one or two arguments. Inside the function, TypeScript treats the optional parameter as potentially undefined, so the implementation should account for that possibility before using it as a string.

Optional parameters are helpful when a function supports additional information without requiring it for every call. They allow developers to keep simple calls concise while still supporting customization.

2. Understanding Default Parameters

A default parameter assigns a fallback value directly in the function signature. The default is used when the corresponding argument is omitted or its value is undefined.

function greetUser(
  name: string,
  greeting: string = "Hello"
): string {
  return greeting + ", " + name + "!";
}

console.log(greetUser("Asha"));
console.log(greetUser("Ravi", "Welcome"));
console.log(greetUser("Maya", undefined));

When the second argument is omitted or passed as undefined, the function uses the default greeting. When a string is provided, the function uses that string instead.

Because the parameter has a default value, callers can omit it. TypeScript infers its type from the default value unless another compatible type annotation is specified. Inside the function, the parameter is treated as having the resolved parameter type rather than being potentially undefined.

3. Optional Parameters vs Default Parameters

Optional and default parameters both allow callers to leave out an argument, but their behavior and syntax are different. An optional parameter may be undefined inside the function, while a default parameter automatically receives its fallback when the argument is missing or undefined.

Feature Optional parameter Default parameter
Syntax value?: string value = "default"
Can be omitted Yes Yes
Value when omitted undefined Fallback value
Value when passed as undefined undefined Fallback value
Best suited for Values that may genuinely be absent Values with a natural fallback
function optionalExample(
  value?: string
): string {
  return value === undefined ? "Missing" : value;
}

function defaultExample(
  value: string = "Default"
): string {
  return value;
}

console.log(optionalExample());
console.log(optionalExample("Custom"));

console.log(defaultExample());
console.log(defaultExample("Custom"));
console.log(defaultExample(undefined));

Choose an optional parameter when the absence of a value is meaningful to the function. Choose a default parameter when the function should use a specific value if the caller does not supply one.

4. Ordering Required, Optional, and Default Parameters

Function parameter order determines how callers supply arguments. In ordinary function signatures, required parameters should come before optional parameters so that argument positions remain unambiguous.

// Valid parameter ordering
function createCourse(
  title: string,
  category?: string
): string {
  return category === undefined
    ? title
    : title + " - " + category;
}

console.log(createCourse("TypeScript"));
console.log(createCourse("TypeScript", "Programming"));

An ordinary optional parameter cannot precede a required parameter in a regular function signature. If callers need to provide a later option while skipping an earlier optional argument, they may have to explicitly pass undefined or the function can be redesigned to accept an options object.

Default-initialized parameters can appear before later required parameters in TypeScript. In that case, callers must supply the argument for the later required parameter, using undefined in the earlier position when they want its default. However, placing required parameters first usually produces a simpler and more readable API.

5. Using Multiple Default Parameters

A function can define multiple default parameters. This is useful when a common operation has several settings with reasonable default values.

function createGreeting(
  name: string,
  greeting: string = "Hello",
  punctuation: string = "!"
): string {
  return greeting + ", " + name + punctuation;
}

console.log(createGreeting("Asha"));
console.log(createGreeting("Ravi", "Welcome"));
console.log(createGreeting("Maya", "Hi", "."));

Every omitted or undefined default parameter receives its own fallback. Callers can override just the settings they need by supplying arguments in the correct order.

However, a long list of positional arguments can become difficult to understand. When a function has several independent options, a single options object often provides a clearer interface and makes call sites easier to maintain.

6. Using Default Parameters with Different Types

Default parameters are not limited to strings. They can be used with numbers, booleans, arrays, object references, and other values that have an appropriate default.

function calculatePrice(
  price: number,
  taxRate: number = 0.1
): number {
  return price + price * taxRate;
}

function getCourseNames(
  courses: string[] = []
): string[] {
  return courses;
}

function describeCourse(
  title: string,
  published: boolean = false
): string {
  return published
    ? title + " is published"
    : title + " is a draft";
}

console.log(calculatePrice(100));
console.log(getCourseNames());
console.log(describeCourse("TypeScript Basics"));

In the price calculation, the default tax rate is used only when a rate is omitted or undefined. In the course example, the function uses an empty array when no course list is supplied.

Use defaults that accurately represent the application's business rules. For example, a default tax rate or currency conversion rate should not be chosen arbitrarily if the value depends on a user's region, product type, or current configuration.

7. Understand undefined and Null

One important detail is that default parameters are activated by an omitted argument or undefined, not by null. JavaScript treats these values differently, and TypeScript can help you model that distinction.

function showMessage(
  message: string | null = "Default message"
): string {
  if (message === null) {
    return "Message was explicitly cleared";
  }

  return message;
}

console.log(showMessage());
console.log(showMessage(undefined));
console.log(showMessage("Hello"));
console.log(showMessage(null));

The first two calls use the default value. Passing a string uses that string, while passing null preserves null because null is an explicitly supplied value permitted by the parameter's declared type.

When null has a meaningful business meaning, include it in the parameter type and handle it explicitly. Do not assume that default values replace every falsy value. Values such as zero, false, and an empty string are also distinct from undefined.

8. Using Nullish Coalescing for Fallbacks

Sometimes a function accepts an optional parameter but wants to decide on a fallback inside its implementation. The nullish coalescing operator (??) provides a concise way to use a default when a value is null or undefined.

function getPageSize(
  requestedSize?: number
): number {
  return requestedSize ?? 20;
}

console.log(getPageSize());
console.log(getPageSize(50));
console.log(getPageSize(0));

The nullish coalescing operator preserves zero because zero is a valid number, even if the application's business rules later decide that a page size of zero should be rejected. In contrast, the logical OR operator (||) uses its fallback whenever the left side is falsy, including zero, false, and an empty string.

Choose the operator based on the intended behavior. Nullish coalescing is usually a better fit when only missing values should trigger a fallback, while logical OR is appropriate when all falsy values should be treated as missing.

9. Optional Parameters in Function Types

Optional and default parameter behavior is also important when describing callback contracts. A function type may include an optional parameter to indicate that callers are allowed to omit the argument.

type GreetingFunction = (
  name: string,
  greeting?: string
) => string;

const greet: GreetingFunction = (
  name,
  greeting = "Hello"
) => {
  return greeting + ", " + name + "!";
};

console.log(greet("Asha"));
console.log(greet("Ravi", "Welcome"));

The function type permits the second argument to be omitted. The implementation provides a default value, so it does not need to manually handle undefined in its function body.

This pattern is useful for event handlers, reusable utilities, and plugin interfaces. Be precise when marking callback parameters optional: the declaration controls how callers are permitted to invoke the callback, not merely whether the implementation uses the argument.

10. Using an Options Object Instead of Many Parameters

When a function has several optional settings, using an object parameter can make the API easier to understand. Each property can have its own type, and default values can be applied through destructuring.

interface CourseOptions {
  category?: string;
  published?: boolean;
  durationMinutes?: number;
}

function createCourse(
  title: string,
  {
    category = "General",
    published = false,
    durationMinutes = 60
  }: CourseOptions = {}
): string {
  return (
    title +
    " | Category: " + category +
    " | Published: " + published +
    " | Duration: " + durationMinutes
  );
}

console.log(createCourse("TypeScript Basics"));

console.log(
  createCourse("Advanced TypeScript", {
    category: "Programming",
    published: true,
    durationMinutes: 120
  })
);

The entire options object has a default value of an empty object, so callers can omit it altogether. Destructuring supplies defaults for individual properties that are missing or undefined.

An options object is especially useful when parameters are independent, optional, or likely to grow over time. It also makes calls more self-documenting because property names clarify the meaning of supplied values.

11. Best Practices for Optional and Default Parameters

Keep required arguments first

Place required parameters before optional parameters to keep calls readable and avoid awkward argument positions.

Choose meaningful default values

A default should reflect a valid application behavior rather than an arbitrary value that could produce incorrect results.

Distinguish missing values from null

Remember that default parameters replace undefined, not null. Include null in a parameter type when it is an intentional input value.

Avoid too many positional parameters

When several independent options exist, prefer a typed options object so callers can specify values by property name.

Model function contracts accurately

Mark a parameter optional only if callers can genuinely omit it. Use a default parameter when the function should automatically supply a fallback.

Common Mistakes to Avoid

Small mistakes in parameter design can make functions confusing or introduce subtle behavior differences. Review these common cases when writing TypeScript function signatures.

  • Using an optional parameter without checking whether it is undefined.
  • Assuming a default parameter replaces null, zero, false, or an empty string.
  • Placing ordinary optional parameters before required parameters.
  • Using many positional options when an object would express the intent more clearly.
  • Making callback parameters optional even though callers must provide them.
  • Choosing defaults that do not reflect actual business rules.

Conclusion

Optional and default parameters make TypeScript functions flexible without sacrificing type safety. Optional parameters represent values that may be absent, while default parameters automatically provide fallback values when arguments are omitted or undefined.

Use optional parameters when the function needs to distinguish between a supplied value and a missing value. Use defaults when a predictable fallback is appropriate, and consider a typed options object when a function has several independent settings. Clear parameter design makes APIs easier to use, understand, test, and maintain.

Code Examples

Optional Parameters

typescript
function greetUser(
  name: string,
  greeting?: string
): string {
  if (greeting === undefined) {
    return "Hello, " + name + "!";
  }

  return greeting + ", " + name + "!";
}

console.log(greetUser("Asha"));
console.log(greetUser("Ravi", "Welcome"));
    

An optional parameter can be omitted by the caller. Inside the function, its value may be undefined, so handle that possibility before using it.

Default Parameters

typescript
function calculatePrice(
  price: number,
  taxRate: number = 0.1
): number {
  return price + price * taxRate;
}

console.log(calculatePrice(100));
console.log(calculatePrice(100, 0.2));
console.log(calculatePrice(100, undefined));
    

A default parameter supplies its fallback when the argument is omitted or explicitly passed as undefined.

Optional Parameters with Nullish Coalescing

typescript
function getPageSize(
  requestedSize?: number
): number {
  return requestedSize ?? 20;
}

console.log(getPageSize());
console.log(getPageSize(50));
console.log(getPageSize(0));
    

Nullish coalescing applies the fallback only when the value is null or undefined, preserving valid falsy values such as zero.

Multiple Default Parameters

typescript
function createGreeting(
  name: string,
  greeting: string = "Hello",
  punctuation: string = "!"
): string {
  return greeting + ", " + name + punctuation;
}

console.log(createGreeting("Asha"));
console.log(createGreeting("Ravi", "Welcome"));
console.log(createGreeting("Maya", "Hi", "."));
    

Each default parameter has its own fallback, allowing callers to override only the values they need.

Typed Options Object

typescript
interface CourseOptions {
  category?: string;
  published?: boolean;
}

function describeCourse(
  title: string,
  {
    category = "General",
    published = false
  }: CourseOptions = {}
): string {
  return title +
    " | " + category +
    " | Published: " + published;
}

console.log(describeCourse("TypeScript Basics"));

console.log(
  describeCourse("Advanced TypeScript", {
    category: "Programming",
    published: true
  })
);
    

A typed options object provides a clear alternative to long lists of optional parameters. Destructuring applies fallback values to omitted or undefined properties.

Pro Tip

Use optional parameters when the function needs to know that a value may be absent, and default parameters when a fallback is always appropriate. Remember that defaults replace omitted arguments and undefined, not null, zero, false, or empty strings.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.