In TypeScript, functions are a fundamental part of the language. They allow you to encapsulate reusable logic and perform specific tasks. One common requirement when defining functions is to handle cases where some parameters might not be provided by the caller. This is where optional parameters come into play.
Optional parameters in TypeScript enable you to specify that certain function parameters can be omitted when the function is called. If a parameter is optional, it can either receive a value or remain undefined. This flexibility is particularly useful for creating robust and flexible functions that can handle various input scenarios.
In TypeScript, you can make a parameter optional by appending a question mark (?) to its name in the function signature. When a parameter is marked as optional, it automatically gets an implicit type of type | undefined, where type is the specified type of the parameter.
Here's a basic example to illustrate how optional parameters work:
1function greet(name?: string) {2if (name) {3console.log(`Hello, ${name}!`);4} else {5console.log('Hello!');6}7}89greet(); // Output: Hello!10greet('Alice'); // Output: Hello, Alice!
In this example, the greet function has an optional parameter name. When you call greet() without any arguments, name is undefined, and the function logs "Hello!". If you provide a name, like greet('Alice'), it logs "Hello, Alice!".
Let's consider a more practical example where optional parameters can be useful. Suppose we have a function that calculates the area of a rectangle. The rectangle might not always have both width and height specified, so we can make these parameters optional.
1function calculateArea(width?: number, height?: number): number {2if (width && height) {3return width * height;4} else {5throw new Error('Both width and height must be provided');6}7}89console.log(calculateArea(10, 5)); // Output: 5010console.log(calculateArea()); // Throws an error
In this example, both width and height are optional parameters. If either of them is not provided when calling the function, the function throws an error.
Sometimes, you might want to provide a default value for an optional parameter if it's not specified. This can be achieved using default parameter syntax in combination with optional parameters.
1function createUser(name: string, age?: number): { name: string; age: number } {2return {3name,4age: age !== undefined ? age : 18, // Default age to 18 if not provided5};6}78console.log(createUser('Alice')); // Output: { name: 'Alice', age: 18 }9console.log(createUser('Bob', 30)); // Output: { name: 'Bob', age: 30 }
In this example, the age parameter is optional. If it's not provided, the function defaults its value to 18.
TypeScript also supports function overloads, which allow you to define multiple signatures for a single function. This can be particularly useful when dealing with optional parameters.
1function formatMessage(message: string): string;2function formatMessage(message: string, prefix?: string): string;34function formatMessage(message: string, prefix?: string): string {5if (prefix) {6return `${prefix}: ${message}`;7} else {8return message;9}10}1112console.log(formatMessage('Hello')); // Output: Hello13console.log(formatMessage('Hello', 'Info')); // Output: Info: Hello
In this example, we define two overloads for the formatMessage function. The first overload takes only a message, while the second overload takes both a message and an optional prefix. This allows TypeScript to understand that the function can be called with either one or two arguments.
In the next section, we'll explore default parameters in TypeScript. Default parameters provide a way to assign a default value to a parameter if no argument is provided when calling the function. This feature complements optional parameters by offering more control over parameter values.
Stay tuned for more insights into TypeScript's powerful features!