TYPESCRIPT
TypeScript Optional Parameter: Syntax, Usage, and Examples
A TypeScript optional parameter lets you define function parameters that are not required when calling the function. This feature gives you flexibility, allowing you to omit certain arguments without causing errors.
How to Use Optional Parameters in TypeScript
You define an optional parameter by adding a ?
after the parameter name in a function definition.
function greet(name?: string): string {
return `Hello, ${name || "Guest"}!`;
}
console.log(greet()); // Output: Hello, Guest!
console.log(greet("Alice")); // Output: Hello, Alice!
Using Default Values for Optional Parameters
You can provide a default value for an optional parameter. If you don’t pass an argument, TypeScript uses the default value.
function orderItem(item: string, quantity: number = 1): string {
return `You ordered ${quantity} ${item}(s).`;
}
console.log(orderItem("apple")); // Output: You ordered 1 apple(s).
console.log(orderItem("banana", 3)); // Output: You ordered 3 banana(s).
Skipping Optional Parameters
Optional parameters must come after required ones. If a function has multiple optional parameters, you can skip some by passing undefined
.
function setUser(name: string, age?: number, city?: string): string {
return `${name} - Age: ${age ?? "Unknown"}, City: ${city ?? "Unknown"}`;
}
console.log(setUser("Alice")); // Output: Alice - Age: Unknown, City: Unknown
console.log(setUser("Bob", undefined, "New York")); // Output: Bob - Age: Unknown, City: New York
When to Use Optional Parameters in TypeScript
Allowing Flexible Function Calls
Optional parameters let you handle different levels of input gracefully.
function logMessage(message: string, timestamp?: Date): void {
console.log(`${timestamp ? timestamp.toISOString() : "No timestamp"}: ${message}`);
}
logMessage("Server started"); // Output: No timestamp: Server started
logMessage("Server crashed", new Date()); // Output: 2023-02-01T12:00:00.000Z: Server crashed
Handling Configuration Options
If you need to pass configuration settings, optional parameters make your function more flexible.
function createUser(username: string, options?: { age?: number; email?: string }): void {
console.log(`Username: ${username}, Age: ${options?.age ?? "Not provided"}, Email: ${options?.email ?? "Not provided"}`);
}
createUser("alice");
// Output: Username: alice, Age: Not provided, Email: Not provided
createUser("bob", { age: 30 });
// Output: Username: bob, Age: 30, Email: Not provided
Supporting Multiple Function Behaviors
Optional parameters let you write functions that handle multiple cases without function overloading.
function fetchData(endpoint: string, cache?: boolean): void {
console.log(`Fetching from ${endpoint} ${cache ? "with cache" : "without cache"}`);
}
fetchData("/users"); // Output: Fetching from /users without cache
fetchData("/posts", true); // Output: Fetching from /posts with cache
Examples of Optional Parameters in TypeScript
Checking If an Optional Parameter Exists
You can check whether an optional parameter was provided using an if
statement.
function printDetails(name: string, age?: number): void {
if (age !== undefined) {
console.log(`${name} is ${age} years old.`);
} else {
console.log(`${name} didn't provide an age.`);
}
}
printDetails("Alice"); // Output: Alice didn't provide an age.
printDetails("Bob", 30); // Output: Bob is 30 years old.
Using Optional Parameters in Class Methods
Optional parameters work well inside class methods, making your code more flexible.
class Product {
name: string;
price: number;
discount?: number;
constructor(name: string, price: number, discount?: number) {
this.name = name;
this.price = price;
this.discount = discount;
}
getPrice(): number {
return this.discount ? this.price * (1 - this.discount / 100) : this.price;
}
}
const product1 = new Product("Laptop", 1000, 10);
const product2 = new Product("Mouse", 50);
console.log(product1.getPrice()); // Output: 900
console.log(product2.getPrice()); // Output: 50
Using Optional Parameters in Async Functions
If you’re working with async functions, optional parameters let you define flexible API calls.
async function fetchUserData(userId: string, includePosts?: boolean): Promise<void> {
console.log(`Fetching data for user ${userId} ${includePosts ? "with posts" : "without posts"}`);
}
fetchUserData("123"); // Output: Fetching data for user 123 without posts
fetchUserData("456", true); // Output: Fetching data for user 456 with posts
Learn More About Optional Parameters in TypeScript
Optional vs. Default Parameters
- Optional parameters don’t have a default value and are
undefined
if you don’t provide them. - Default parameters have a predefined fallback value when omitted.
function optionalParam(name?: string): string {
return `Hello, ${name ?? "Guest"}!`;
}
function defaultParam(name: string = "Guest"): string {
return `Hello, ${name}!`;
}
console.log(optionalParam()); // Output: Hello, Guest!
console.log(defaultParam()); // Output: Hello, Guest!
Multiple Optional Parameters
Your function can have multiple optional parameters, but required parameters must always come first.
function describeUser(name: string, age?: number, country?: string): string {
return `${name} - Age: ${age ?? "Unknown"}, Country: ${country ?? "Unknown"}`;
}
console.log(describeUser("Alice")); // Output: Alice - Age: Unknown, Country: Unknown
console.log(describeUser("Bob", 30)); // Output: Bob - Age: 30, Country: Unknown
console.log(describeUser("Charlie", 25, "USA")); // Output: Charlie - Age: 25, Country: USA
Optional Parameters in Function Overloading
You can combine optional parameters with function overloading to define multiple ways to call a function.
function getData(id: number): string;
function getData(name: string): string;
function getData(param: number | string, verbose?: boolean): string {
if (typeof param === "number") {
return `Fetching data for ID: ${param} ${verbose ? "(verbose mode)" : ""}`;
} else {
return `Fetching data for Name: ${param} ${verbose ? "(verbose mode)" : ""}`;
}
}
console.log(getData(123)); // Output: Fetching data for ID: 123
console.log(getData("Alice", true)); // Output: Fetching data for Name: Alice (verbose mode)
How to Skip Optional Parameters
If a function has multiple optional parameters, you can skip one by passing undefined
.
function logError(message: string, level?: string, timestamp?: Date): void {
console.log(`[${level ?? "INFO"}] ${timestamp?.toISOString() ?? "No timestamp"}: ${message}`);
}
logError("Something went wrong"); // Output: [INFO] No timestamp: Something went wrong
logError("Critical issue", "ERROR", new Date()); // Output: [ERROR] 2023-02-01T12:00:00.000Z: Critical issue
TypeScript optional parameters give you flexibility when writing functions, class methods, and async calls. They make function calls more intuitive, reduce unnecessary checks, and improve code readability.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.