![]() |
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
Syntaxfunction f(x?: Type) {
// ...
} Parameters:
Example 1: Optional Parameters in FunctionsIn 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.
Output: 5
9 Example 2: Optional Parameters in CallbacksIn 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.
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. ConclusionOptional 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 ParametersWhat 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?
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?
|
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |