Typescript default parameters
Created By: chatGPT
Default parameters in TypeScript allow you to initialize function parameters with default values if no value or
undefined
is passed. This feature enhances the flexibility and usability of functions without compromising their clarity.function greet(name: string = 'Guest'): string {
return `Hello, ${name}!`;
}
console.log(greet()); // Output: Hello, Guest!
console.log(greet('Alice')); // Output: Hello, Alice!
You can also use default parameters alongside other parameters. Just ensure that all parameters with default values come after any required parameters.
function multiply(a: number, b: number = 1): number {
return a * b;
}
console.log(multiply(5)); // Output: 5
console.log(multiply(5, 2)); // Output: 10
Moreover, default parameters can be set based on other parameters, which can increase functionality significantly. However, make sure to handle cases where parameters might be undefined.
function calculateTotal(price: number, tax: number = price * 0.1): number {
return price + tax;
}
console.log(calculateTotal(100)); // Output: 110
console.log(calculateTotal(100, 15)); // Output: 115
Type inference works well with default parameters in TypeScript. When you provide a default value, TypeScript infers the type from the provided value, making it easier to manage types without explicitly declaring them each time.
function log(message: string = 'No message provided.'): void {
console.log(message);
}
log(); // Output: No message provided.
log('A custom message.'); // Output: A custom message.
Remember that default parameters can improve the readability of your code and reduce the need for additional checks inside function bodies. This way, you can simplify your logic.
function joinStrings(prefix: string = 'Hi', name: string = 'There'): string {
return `${prefix}, ${name}!`;
}
console.log(joinStrings()); // Output: Hi, There!
console.log(joinStrings('Hello', 'World')); // Output: Hello, World!