Multiple Parameters in TypeScript
Functions can accept multiple parameters, allowing you to pass several values to perform complex operations. In TypeScript, every parameter must have a defined type, ensuring that the correct data types are passed when calling the function.
Basic Syntax
function functionName(param1: type1, param2: type2, param3: type3): returnType {
// function body
return value;
}Simple Example with Two Parameters
function add(a: number, b: number): number {
return a + b;
}
const result: number = add(10, 20);
console.log(`10 + 20 = ${result}`);Output:
10 + 20 = 30Example with Three Parameters
function sum(a: number, b: number, c: number): number {
return a + b + c;
}
const result: number = sum(5, 10, 15);
console.log(`5 + 10 + 15 = ${result}`);Output:
5 + 10 + 15 = 30Different Data Types
You can mix different data types in parameters. Notice how TypeScript ensures type safety:
function displayInfo(name: string, age: number, height: number): void {
console.log(`Name: ${name}`);
console.log(`Age: ${age} years`);
console.log(`Height: ${height} meters`);
}
displayInfo("Alice", 25, 1.65);
// The following would throw a TS error:
// displayInfo(25, "Alice", 1.65); // Error: Argument of type 'number' is not assignable to 'string'Output:
Name: Alice
Age: 25 years
Height: 1.65 metersRectangle Area Calculator
A practical example calculating the area of a rectangle:
function calculateRectangleArea(length: number, width: number): number {
return length * width;
}
const area: number = calculateRectangleArea(5.5, 3.2);
console.log(`Rectangle Area: ${area} square units`);Output:
Rectangle Area: 17.6 square unitsString Formatting Function
You can easily concatenate strings using template literals:
function formatMessage(greeting: string, name: string, punctuation: string): string {
return `${greeting}, ${name}${punctuation}`;
}
const message1: string = formatMessage("Hello", "Alice", "!");
const message2: string = formatMessage("Good morning", "Bob", ".");
console.log(message1);
console.log(message2);Output:
Hello, Alice!
Good morning, Bob.Grade Calculator
Calculate a final grade from multiple components:
function calculateFinalGrade(homework: number, midterm: number, final: number): number {
// 30% homework, 30% midterm, 40% final
return (homework * 0.30) + (midterm * 0.30) + (final * 0.40);
}
const finalGrade: number = calculateFinalGrade(85, 90, 88);
console.log(`Final Grade: ${finalGrade}%`);Output:
Final Grade: 87.9%Optional Parameters (?)
Unlike C++, TypeScript has a specific syntax for optional parameters. You add a question mark (?) after the parameter name to indicate that it’s okay to skip it. Optional parameters must come after required parameters.
function buildName(firstName: string, lastName?: string): string {
if (lastName) {
return `${firstName} ${lastName}`;
} else {
return firstName;
}
}
console.log(buildName("Bob")); // OK: returns "Bob"
console.log(buildName("Bob", "Adams")); // OK: returns "Bob Adams"Parameter Order Matters
The order in which you pass arguments must match the function definition:
function displayOrder(first: number, second: number, third: number): void {
console.log(`First: ${first}`);
console.log(`Second: ${second}`);
console.log(`Third: ${third}`);
}
displayOrder(10, 20, 30);Output:
First: 10
Second: 20
Third: 30Complex Example: Tuples for Multiple Returns
Instead of passing pointers/references like in C++, TypeScript can easily return multiple values using Tuples or Objects:
const PI = Math.PI;
// Notice the return type is a tuple [number, number]
function circleProperties(radius: number): [number, number] {
const area = PI * radius * radius;
const circumference = 2 * PI * radius;
return [area, circumference];
}
const r = 5.0;
const [calculatedArea, calculatedCircumference] = circleProperties(r);
console.log(`Circle with radius ${r}:`);
console.log(`Area: ${calculatedArea.toFixed(4)}`);
console.log(`Circumference: ${calculatedCircumference.toFixed(4)}`);Output:
Circle with radius 5:
Area: 78.5398
Circumference: 31.4159Best Practices
- Limit the number of parameters: If you need more than 3-4 parameters, pass a configuration object interface instead.
interface UserConfig { name: string; age: number; email: string; } function createUser(config: UserConfig) {} - Use meaningful names:
calculateArea(length, width)is clearer thancalc(a, b). - Group related parameters: Keep parameters that work together adjacent.
- Consider parameter order: Put required parameters first, optional parameters later.
Common Mistakes
Wrong Number of Arguments
TypeScript strictly checks the number of arguments (unless you use optional parameters ?):
function add(a: number, b: number): number {
return a + b;
}
// Wrong: too few arguments
// add(5); // Error: Expected 2 arguments, but got 1.
// Wrong: too many arguments
// add(5, 10, 15); // Error: Expected 2 arguments, but got 3.
// Correct
add(5, 10); // ✓Wrong Argument Types
function display(number: number, text: string): void {
console.log(`${text}: ${number}`);
}
// Wrong order - types don't match
// display("Score", 100); // Error: Argument of type 'string' is not assignable to parameter of type 'number'
// Correct
display(100, "Score"); // ✓Practice Exercises
- BMI Calculator: Create a function that takes weight (kg) and height (m) typed as numbers and returns the BMI.
- Temperature Converter: Write a function that takes a temperature (number) and a unit (
'C' | 'F') and converts it. - Max of Three: Create a function that finds the maximum of three numbers.
Next Steps
- Learn about Default Parameters to provide default values for parameters.
- Explore REST parameters (
...args: type[]) for an infinite number of arguments.