Typescript Optional And Default Parameters Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    6 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of TypeScript Optional and Default Parameters

TypeScript Optional and Default Parameters

Optional Parameters: Optional parameters allow a function to be called with or without a particular argument. This is indicated by appending a question mark (?) to the parameter name in the function signature.

Syntax:

function greet(name?: string): string {
    if (name) {
        return `Hello, ${name}!`;
    } else {
        return "Hello!";
    }
}

Usage:

  • When a function is called without the optional parameter, the value of that parameter inside the function is undefined.
  • Optional parameters must come after all required parameters in the function signature.

Example:

function createPerson(name: string, age?: number): { name: string, age?: number } {
    return { name, age };
}

console.log(createPerson("Alice")); // Output: { name: "Alice" }
console.log(createPerson("Bob", 25)); // Output: { name: "Bob", age: 25 }

Default Parameters: Default parameters provide a fallback value for a function parameter if no argument is passed, or if the passed argument is undefined. This simplifies function logic and eliminates the need for manual checks.

Syntax:

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

Usage:

  • Default parameters can be used in conjunction with optional parameters. If both are present, the default value will apply when the parameter is undefined.
  • Default parameters can also be non-primitive types, such as objects or arrays, or functions.

Example:

function calculateDiscount(price: number, discountRate: number = 0.1): number {
    return price * (1 - discountRate);
}

console.log(calculateDiscount(100)); // Output: 90 (10% discount applied)
console.log(calculateDiscount(100, 0.2)); // Output: 80 (20% discount applied)

Combining Optional and Default Parameters: It's common to combine optional and default parameters in function definitions to handle a variety of input scenarios gracefully.

Example:

function configureSettings(config: { theme?: string, fontSize?: number } = {}): void {
    const { theme = "light", fontSize = 16 } = config;
    console.log(`Theme: ${theme}, Font Size: ${fontSize}`);
}

configureSettings(); // Output: Theme: light, Font Size: 16
configureSettings({ theme: "dark" }); // Output: Theme: dark, Font Size: 16
configureSettings({ fontSize: 14 }); // Output: Theme: light, Font Size: 14
configureSettings({ theme: "dark", fontSize: 14 }); // Output: Theme: dark, Font Size: 14

Benefits:

  • Reduced Errors: Default parameters prevent the need for additional code to handle undefined values.
  • Improved Readability: Using optional and default parameters makes the function intention clearer and easier to understand.
  • Flexibility: Functions can handle a wider range of input scenarios without needing multiple overloads.
  • Maintainability: Changes in default values or optional parameters are localized, reducing the risk of propagating bugs.

Best Practices:

  • Place Optional and Default Parameters Last: This ensures that all required parameters are provided when the function is called.
  • Use Descriptive Default Values: Choose default values that make sense in the context of the function.
  • Avoid Complex Default Values: Keep default values simple to avoid unnecessary code and complexity.

Conclusion: Mastering optional and default parameters in TypeScript enables developers to write more robust and expressive functions. By leveraging these features effectively, you can enhance the quality of your code and improve the user experience.


Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement TypeScript Optional and Default Parameters

Optional Parameters

Optional parameters are parameters that may or may not be passed to a function. In TypeScript, you can make a parameter optional by adding a ? at the end of the parameter name.

Step-by-Step Example:

  1. Function Definition:
function printName(firstName: string, lastName?: string) {
    if (lastName) {
        console.log(`Full Name: ${firstName} ${lastName}`);
    } else {
        console.log(`First Name: ${firstName}`);
    }
}
  1. Calling the Function:
printName("John");        // Output: First Name: John
printName("John", "Doe"); // Output: Full Name: John Doe

In this example, lastName is an optional parameter. When lastName is not provided, the function simply prints the first name.

Default Parameters

Default parameters allow you to specify a default value that a parameter should take if no argument is passed, or if the undefined value is explicitly passed.

Step-by-Step Example:

  1. Function Definition:
function printName(firstName: string, lastName: string = "Doe") {
    console.log(`Full Name: ${firstName} ${lastName}`);
}
  1. Calling the Function:
printName("John");        // Output: Full Name: John Doe
printName("John", "Smith"); // Output: Full Name: John Smith

In this example, lastName has a default value of "Doe". If lastName is not provided, it defaults to "Doe".

Combining Optional and Default Parameters

You can combine both optional and default parameters in a function.

Step-by-Step Example:

  1. Function Definition:
function printName(firstName: string, lastName?: string, middleName: string = "") {
    if (lastName) {
        console.log(`Full Name: ${firstName} ${middleName} ${lastName}`);
    } else {
        console.log(`First Name: ${firstName}`);
    }
}
  1. Calling the Function:
printName("John");             // Output: First Name: John
printName("John", "Doe");      // Output: Full Name: John  Doe
printName("John", "Doe", "C.");  // Output: Full Name: John C. Doe
printName("John", undefined, "C.");  // Output: Full Name: John C. Doe

In this example, lastName is optional, and middleName has a default value of "". When middleName is not provided, it defaults to "".

Key Points to Remember:

  • Optional Parameters: Use ? after the parameter name.
  • Default Parameters: Assign a default value to the parameter.

Optional and default parameters make functions more flexible, allowing you to handle different scenarios easily.

Top 10 Interview Questions & Answers on TypeScript Optional and Default Parameters

1. What are Optional Parameters in TypeScript?

Answer: Optional parameters in TypeScript are parameters that may or may not be provided when a function is called. They are denoted by placing a question mark (?) after the parameter name in the function signature. This allows the function to be called with fewer arguments than defined.

function greet(name?: string) {
    return name ? `Hello, ${name}!` : 'Hello, world!';
}
console.log(greet('Alice')); // Output: Hello, Alice!
console.log(greet());       // Output: Hello, world!

2. How do Default Parameters work in TypeScript?

Answer: Default parameters in TypeScript allow you to set a default value for a function parameter if no value or undefined is passed in the function call. This feature avoids undefined values for the parameters.

function greet(name: string = 'world') {
    return `Hello, ${name}!`;
}
console.log(greet('Bob'));  // Output: Hello, Bob!
console.log(greet());      // Output: Hello, world!

3. Can you use Optional and Default Parameters in the same function?

Answer: Yes, you can use both optional and default parameters in the same function. However, it's essential to ensure that default parameters come after any non-default and non-optional parameters, as it improves code readability and prevents ambiguity.

function greet(name: string = 'World', greeting?: string) {
    return greeting ? `${greeting}, ${name}!` : `Hello, ${name}!`;
}
console.log(greet('Alice'));     // Output: Hello, Alice!
console.log(greet(undefined, 'Hi')); // Output: Hi, World!

4. What is the difference between Optional and Default Parameters?

Answer: Optional parameters are parameters that are optional when calling a function (name?: string). If no argument is provided, the parameter's value is undefined. Default parameters are parameters that have a default value assigned, which is used if no argument or undefined is passed (name: string = 'default').

5. Can Optional and Default Parameters be used with arrow functions in TypeScript?

Answer: Absolutely, you can use optional and default parameters with arrow functions in TypeScript just as you would with regular functions.

const greet = (name?: string) => {
    return name ? `Hello, ${name}!` : 'Hello, world!';
};
console.log(greet('Charlie'));  // Output: Hello, Charlie!
console.log(greet());            // Output: Hello, world!

const greetWithDefault = (name: string = 'World') => {
    return `Hola, ${name}!`;
};
console.log(greetWithDefault('Eve')); // Output: Hola, Eve!
console.log(greetWithDefault());      // Output: Hola, World!

6. What are the benefits of using Optional Parameters?

Answer: Optional parameters simplify function signatures by allowing them to be called with fewer arguments. This flexibility makes the functions more user-friendly and can prevent errors caused by passing incorrect or missing values.

7. What are the benefits of using Default Parameters?

Answer: Default parameters enhance code readability by setting expected default values. They also provide a safeguard, ensuring that functions behave correctly even if certain arguments are omitted or explicitly undefined.

8. Can you use Optional and Default Parameters with TypeScript interfaces and types?

Answer: While interfaces and types can define what arguments a function should take, they don’t directly handle optional or default parameters. However, you can use them to define function types that include optional and default parameters.

type GreetFunction = (name?: string) => string;

const greet: GreetFunction = (name) => {
    return name ? `Hello, ${name}!` : 'Hello, world!';
};
console.log(greet('Dana')); // Output: Hello, Dana!
console.log(greet());      // Output: Hello, world!

9. What happens if you declare an optional parameter before a required one?

Answer: In TypeScript, if an optional parameter is declared before a required parameter in a function signature, it results in a compile-time error. TypeScript enforces that required parameters must come before optional ones to maintain clarity and avoid confusion.

// This will cause a compile-time error
function greet(greeting?: string, name: string) {
    return `${greeting}, ${name}!`;
}
// Error: A required parameter cannot follow an optional parameter.

10. Can you use Optional and Default Parameters in Constructor Functions within Classes?

Answer: Yes, you can use optional and default parameters in constructor functions within TypeScript classes. This makes it flexible to instantiate objects with varying numbers and types of arguments.

You May Like This Related .NET Topic

Login to post a comment.