TypeScript Optional Parameters
Last Updated :
22 Jan, 2025
Improve
Optional parameters in TypeScript allow functions to be called without specifying all arguments, enhancing flexibility and code readability.
- Denoted by appending a ? to the parameter name.
- Optional parameters must follow the required parameters in function definitions.
Syntax
function functionName(param1: type, param2?: type): returnType {
// function body
}
Parameters:
- param1: A required parameter of the specified type.
- param2?: An optional parameter; if omitted, its value is undefined.
function greet(name: string, greeting?: string): string {
if (greeting) {
return `${greeting}, ${name}!`;
}
return `Hello, ${name}!`;
}
console.log(greet("Alice"));
console.log(greet("Bob", "Good morning"));
- The greet function has two parameters: name (required) and greeting (optional).
- If greeting is provided, it customizes the message; otherwise, it defaults to "Hello".
Greeting Function with Optional Parameter
function greet(name: string, greeting?: string): string {
if (greeting) {
return `${greeting}, ${name}!`;
} else {
return `Hello, ${name}!`;
}
}
console.log(greet("Alice"));
console.log(greet("Bob", "Good morning"));
- The greet function has two parameters: name (required) and greeting (optional).
- If greeting is provided, it customizes the message; otherwise, it defaults to "Hello".
Output:
Hello, Alice!
Good morning, Bob!
Function with Multiple Optional Parameters
function createUser(username: string, age?: number, email?: string): string {
let userInfo = `Username: ${username}`;
if (age !== undefined) {
userInfo += `, Age: ${age}`;
}
if (email !== undefined) {
userInfo += `, Email: ${email}`;
}
return userInfo;
}
console.log(createUser("john_doe"));
console.log(createUser("jane_doe", 28));
console.log(createUser("sam_smith", 30, "sam@example.com"));
- The createUser function accepts username (required), age, and email (both optional).
- It constructs a user information string based on the provided arguments.
Output:
Username: john_doe
Username: jane_doe, Age: 28
Username: sam_smith, Age: 30, Email: sam@example.com
Best Practices for Using TypeScript Optional Parameters
- Place Optional Parameters After Required Ones: Always define optional parameters following all required parameters to maintain clarity and prevent errors.
- Provide Default Values When Appropriate: Assign default values to optional parameters to ensure predictable behavior when arguments are omitted.
- Use Union Types for Flexibility: Consider using union types for optional parameters to clearly specify the types that are allowed, enhancing type safety.