TypeScript Default Parameters

This chapter explores default parameters in TypeScript, a feature that enhances function flexibility by assigning default values to parameters. Default parameters simplify function logic and reduce the need for additional checks or conditions within the function body.

Chapter Goal

  • To understand what default parameters are and their purpose in TypeScript.
  • To learn how to define and use default parameters effectively.
  • To explore practical applications and scenarios where default parameters are beneficial.

Key Characteristics for TypeScript Default Parameters

  • Default Assignment: Automatically assigns a value to a parameter if it is not provided during the function call.
  • Flexibility: Allows functions to operate with fewer arguments while maintaining predictable behavior.
  • Type Safety: Ensures that default values adhere to the specified parameter type.
  • Concise Logic: Reduces the need for explicit checks and conditional statements.
  • Backward Compatibility: Functions with default parameters are compatible with existing TypeScript code.

Basic Rules for TypeScript Default Parameters

  1. Use the = operator to assign default values to parameters.
  2. Default parameters must come after required parameters.
  3. Ensure default values match the expected type of the parameter.
  4. Avoid using complex expressions as default values unless necessary.
  5. Combine default parameters with optional parameters for added flexibility.

Best Practices

  1. Use meaningful default values that make sense in the context of the function.
  2. Document the behavior of default parameters for better code readability.
  3. Avoid mixing too many default and required parameters to maintain clarity.
  4. Test functions with and without default parameters to ensure consistent behavior.
  5. Use default parameters to reduce redundancy and improve maintainability.

Syntax Table

Serial No Component Syntax Example Description
1 Basic Default Parameter function greet(name: string = ‘Guest’): void {} Assigns a default value to the name parameter.
2 Multiple Defaults function configure(width: number = 100, height: number = 50): void {} Assigns default values to multiple parameters.
3 Default with Optional function log(message?: string, level: string = ‘INFO’): void {} Combines optional and default parameters.
4 Default with Callback function onClick(callback: () => void = () => {}): void {} Uses a default value for a callback parameter.

Syntax Explanation

1. Basic Default Parameter

What is a Basic Default Parameter

A parameter that is assigned a predefined value when not provided by the caller.

Syntax

function greet(name: string = ‘Guest’): void {

  console.log(`Hello, ${name}!`);

}

Detailed Explanation

  • The name parameter defaults to ‘Guest’ if no value is provided.
  • This ensures that the function has predictable behavior regardless of whether an argument is passed.
  • Default parameters are especially useful when the majority of function calls use the same value for a parameter.

Example

function welcome(name: string = ‘User’): void {

  console.log(`Welcome, ${name}!`);

}

 

welcome(); // Output: Welcome, User!

welcome(‘Alice’); // Output: Welcome, Alice!

Output

Welcome, User!

Welcome, Alice!

Notes

  • Default parameters reduce boilerplate code and simplify function implementation.

Warnings

  • Ensure default values align with the expected behavior of the function to avoid confusion.

2. Multiple Default Parameters

What are Multiple Default Parameters

A function that assigns default values to more than one parameter.

Syntax

function configure(width: number = 100, height: number = 50): void {

  console.log(`Width: ${width}, Height: ${height}`);

}

Detailed Explanation

  • Each parameter is assigned its own default value.
  • Parameters with default values must still adhere to the type annotations.
  • Callers can override the defaults by providing specific arguments during the function call.

Example

function setDimensions(width: number = 200, height: number = 100): void {

  console.log(`Width: ${width}, Height: ${height}`);

}

 

setDimensions(); // Output: Width: 200, Height: 100

setDimensions(300); // Output: Width: 300, Height: 100

setDimensions(300, 150); // Output: Width: 300, Height: 150

Output

Width: 200, Height: 100

Width: 300, Height: 100

Width: 300, Height: 150

Notes

  • Providing meaningful default values reduces the need for excessive function overloads.

Warnings

  • Ensure the order of parameters is logical to avoid ambiguity when calling the function.

3. Default with Optional Parameter

What is a Default Parameter Combined with an Optional Parameter

A function that combines default values with optional parameters for greater flexibility.

Syntax

function log(message?: string, level: string = ‘INFO’): void {

  console.log(`[${level}]: ${message ?? ‘No message provided’}`);

}

Detailed Explanation

  • The level parameter has a default value, while message is optional.
  • This allows the function to handle different combinations of arguments gracefully.
  • The ?? operator is used to provide a fallback value for the optional parameter.

Example

log(); // Output: [INFO]: No message provided

log(‘System started’); // Output: [INFO]: System started

log(‘Error occurred’, ‘ERROR’); // Output: [ERROR]: Error occurred

Output

[INFO]: No message provided

[INFO]: System started

[ERROR]: Error occurred

Notes

  • This combination is ideal for creating functions with varying input requirements, such as logging or configuration.

Warnings

  • Avoid excessive mixing of optional and default parameters, as this can make the function signature harder to understand.

4. Default with Callback

What is a Default Callback Parameter

A parameter that defaults to a predefined callback function.

Syntax

function onClick(callback: () => void = () => {}): void {

  callback();

}

Detailed Explanation

  • If no callback is provided, the function uses the default implementation.
  • This ensures that the function remains functional even when no arguments are passed.
  • Default callbacks are particularly useful for event handling or asynchronous operations.

Example

function execute(action: () => void = () => console.log(‘Default action executed’)): void {

  action();

}

 

execute(); // Output: Default action executed

execute(() => console.log(‘Custom action executed’)); // Output: Custom action executed

Output

Default action executed

Custom action executed

Notes

  • Use default callbacks sparingly to avoid unintended side effects.

Warnings

  • Ensure the default callback is lightweight and does not introduce unnecessary computational overhead.

Project Name

Dynamic Settings Configuration

Project Goal

Demonstrates how to use default parameters to simplify dynamic settings in an application.

Code for This Project

function configureSettings(theme: string = 'light', language: string = 'en', autoSave: boolean = true): void {

  console.log(`Theme: ${theme}, Language: ${language}, AutoSave: ${autoSave}`);

}




configureSettings(); // Output: Theme: light, Language: en, AutoSave: true

configureSettings('dark', 'fr'); // Output: Theme: dark, Language: fr, AutoSave: true

configureSettings('dark', 'fr', false); // Output: Theme: dark, Language: fr, AutoSave: false

Save and Run

  1. Save the code using software like Visual Studio Code or your preferred TypeScript editor. Compile the TypeScript code using tsc settings.ts.
  2. Run the resulting JavaScript file using node settings.js.

Expected Output

Theme: light, Language: en, AutoSave: true

Theme: dark, Language: fr, AutoSave: true

Theme: dark, Language: fr, AutoSave: false

Insights

  • Default parameters enhance function usability by reducing the number of required arguments.
  • They simplify configuration and setup processes in real-world applications.
  • Practical examples like settings management demonstrate their flexibility and utility.

Key Takeaways

  • Default parameters improve code readability and reduce boilerplate.
  • Use them wisely to provide meaningful defaults and simplify function logic.
  • Combine default parameters with optional ones for maximum flexibility in function design.