Careeroza
Optional Default and Rest Parameters
Optional and Default Parameters
param?: T makes a parameter optional (its type becomes T | undefined). param = value gives a default and makes it optional automatically. Optional parameters must come after required ones.
Example
function formatPrice(amount: number, currency = "INR", decimals?: number): string {
const fixed = decimals === undefined ? amount.toString() : amount.toFixed(decimals);
return currency + " " + fixed;
}
console.log(formatPrice(499));
console.log(formatPrice(499, "USD"));
console.log(formatPrice(499, "INR", 2));Output
INR 499 USD 499 INR 499.00
Rest Parameters
Example
A rest parameter collects any number of arguments into an array. Its type is always an array type.
function cartTotal(...prices: number[]): number {
return prices.reduce((sum, p) => sum + p, 0);
}
function tagLine(label: string, ...tags: string[]): string {
return label + ": " + tags.map((t) => "#" + t).join(" ");
}
console.log(cartTotal());
console.log(cartTotal(199, 349, 899));
console.log(tagLine("Product", "sale", "electronics"));Output
0 1447 Product: #sale #electronics
Object Parameters with Defaults
Example
For functions with many options, pass one object and destructure it with defaults. Callers can then pass options in any order.
type SearchOptions = { query: string; page?: number; pageSize?: number; sort?: "price" | "rating" };
function search({ query, page = 1, pageSize = 20, sort = "rating" }: SearchOptions): string {
return `q=${query}&page=${page}&size=${pageSize}&sort=${sort}`;
}
console.log(search({ query: "shoes" }));
console.log(search({ query: "laptop", sort: "price", page: 3 }));Output
q=shoes&page=1&size=20&sort=rating q=laptop&page=3&size=20&sort=price