In TypeScript, specifying optional parameters for functions is straightforward. You can mark a parameter as optional by adding a question mark ? after its name. This allows you to omit the parameter when calling the function.
Here is a concrete example:
typescriptfunction greet(name: string, age?: number) { if (age !== undefined) { console.log(`Hello, my name is ${name} and I am ${age} years old.`); } else { console.log(`Hello, my name is ${name}.`); } } ... (the code as is)
In this example, the greet function accepts two parameters: name (required) and age (optional). When calling the greet function, you can pass only the name parameter, such as greet("Alice"); or you can pass both name and age parameters, such as greet("Bob", 25).
When the age parameter is omitted, the function internally checks if age is undefined to determine which greeting to print. This approach enhances the function's flexibility, enabling it to execute different operations based on the provided parameters.