Horje
TypeScript Optional Parameters

Optional parameters in TypeScript allow you to make parameters optional in function definitions. This means you can call the function without specifying all the parameters. The “?” symbol is used to denote optional parameters.

Key Points

  • Optional Parameters: Represented by “?” in TypeScript, making it non-mandatory to pass a value.
  • Type Safety: TypeScript ensures that every function call is checked for parameter count and types, issuing errors when mismatches occur.
  • Syntax: Use the “?” symbol after the parameter name.

Syntax

function f(x?: Type) {
  // ...
}

Parameters:

  • f is the name of the function that you are defining.
  • x is the name of the parameter.
  • x? is the optional parameter,? represent the optional feature.
  • Type is the data type you want to pass as a parameter.

Example 1: Optional Parameters in Functions

In this example, we define a function add where num1 is a mandatory parameter and num2 is optional. The function returns the sum of num1 and num2 if num2 is provided, otherwise it returns num1.

JavaScript
function add(num1: number, num2?: number): void {
  if (num2 !== undefined) {
    console.log(num1 + num2);
  } else {
    console.log(num1);
  }
}

// Example Usage
add(5);         // Output: 5
add(5, 4);      // Output: 9

Output:

5
9

Example 2: Optional Parameters in Callbacks

In this example, we defines a Callback interface for handling results or errors, then simulates an asynchronous operation with fun(), randomly invoking the callback with success or error after one second, processed by handler.

JavaScript
interface Callback {
    (result: string, error?: string): void;
}

function fun(callback: Callback) {
    setTimeout(() => {
        const success = Math.random() < 0.5;
        if (success) {
            callback('Operation succeeded');
        } else {
            callback('undefined', 'Operation failed');
        }
    }, 1000);
}

function handler(result: string, error?: string) {
    if (error) {
        console.error('Error:', error);
    } else {
        console.log('Success:', result);
    }
}
fun(handler);

Output:

Success: Operation succeeded

Note: When writing a function type for a callback, never write an optional parameter unless you intend to call the function without passing that argument.

Conclusion

Optional parameters in TypeScript enhance function flexibility while maintaining type safety. By using the “?” symbol, you can define functions that can be called with varying numbers of arguments, helping you write more versatile and robust code.

FAQs-TypeScript Optional Parameters

What happens if an optional parameter is not provided in a TypeScript function call?

If an optional parameter is not provided, its value is undefined by default. This allows the function to check for undefined and handle the case where the parameter is omitted.

Can you have required parameters after optional parameters in TypeScript?

No, in TypeScript, required parameters cannot follow optional parameters. All optional parameters must be placed after any required parameters in the function signature. This ensures that function calls remain clear and unambiguous.

Can optional parameters have default values in TypeScript?

Yes, optional parameters can be given default values. If an argument for that parameter is not provided, the parameter will take the default value specified. This combines the concept of optional parameters with default parameters.

function example(param: string = "default") {
// Function body
}

Why should you avoid optional parameters in callback function types unless necessary?

Optional parameters in callback function types should be avoided unless you intend to call the callback without that argument. This ensures that the function signature is clear and predictable. Including unnecessary optional parameters can lead to confusion and potential bugs in function implementation and usage.

How do optional parameters affect function type definitions in TypeScript?

In function type definitions, optional parameters are denoted with a question mark (?) after the parameter name. This signifies that the parameter may or may not be provided when the function is called, providing flexibility in function signatures.

type ExampleFunction = (param1: string, param2?: number) => void;



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
React-Bootstrap Custom Accordions React-Bootstrap Custom Accordions
Create an Interactive Quiz App using React-Native? Create an Interactive Quiz App using React-Native?
Create a Memory Pair Game using React-Native Create a Memory Pair Game using React-Native
Scientific Calculator using React Scientific Calculator using React
Agile Software Development Methodology &amp; Framework Agile Software Development Methodology &amp; Framework

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12