TypeScript Parameters
Understanding function parameters and type annotations
📥 What are TypeScript Parameters?
Parameters are variables listed in a function definition that receive values when the function is called. TypeScript requires type annotations for parameters, ensuring type safety and preventing runtime errors in your applications.
// Function with typed parameters
function addNumbers(x: number, y: number): number {
return x + y;
}
console.log(addNumbers(5, 10));
Output:
15
Parameter Types
Primitive Types
Basic data type parameters
function demo(
name: string,
age: number,
active: boolean
) { }
Object Parameters
Pass objects with typed properties
function process(
user: { name: string; age: number }
) { }
Array Parameters
Accept arrays of specific types
function sum(
numbers: number[]
): number { }
Union Types
Multiple possible types
function format(
value: string | number
) { }
🔹 Basic Parameter Types
Define parameters with primitive types:
// String parameter
function sayHello(name: string): void {
console.log(`Hello, ${name}!`);
}
// Number parameter
function square(num: number): number {
return num * num;
}
// Boolean parameter
function toggleStatus(isActive: boolean): string {
return isActive ? "Active" : "Inactive";
}
sayHello("Alice");
console.log(square(4));
console.log(toggleStatus(true));
Output:
Hello, Alice!
16
Active
🔹 Multiple Parameters
Functions can accept multiple typed parameters:
function calculateTotal(
price: number,
quantity: number,
taxRate: number
): number {
const subtotal = price * quantity;
const tax = subtotal * taxRate;
return subtotal + tax;
}
const total = calculateTotal(10, 3, 0.08);
console.log(`Total: $${total.toFixed(2)}`);
Output:
Total: $32.40
🔹 Object Parameters
Pass objects with defined structure:
// Object parameter with inline type
function displayUser(user: { name: string; age: number; email: string }): void {
console.log(`Name: ${user.name}`);
console.log(`Age: ${user.age}`);
console.log(`Email: ${user.email}`);
}
displayUser({
name: "John Doe",
age: 28,
email: "[email protected]"
});
Output:
🔹 Array Parameters
Work with arrays of specific types:
// Array of numbers
function sumArray(numbers: number[]): number {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
// Array of strings
function joinNames(names: string[]): string {
return names.join(", ");
}
console.log(sumArray([1, 2, 3, 4, 5]));
console.log(joinNames(["Alice", "Bob", "Charlie"]));
Output:
15
Alice, Bob, Charlie
🔹 Union Type Parameters
Accept multiple possible types:
function formatValue(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
} else {
return value.toFixed(2);
}
}
console.log(formatValue("hello"));
console.log(formatValue(42.5678));
Output:
HELLO
42.57
🔹 Type Aliases for Parameters
Create reusable type definitions:
// Define a type alias
type User = {
id: number;
name: string;
email: string;
};
// Use the type alias as parameter
function greetUser(user: User): string {
return `Welcome, ${user.name}!`;
}
const newUser: User = {
id: 1,
name: "Alice",
email: "[email protected]"
};
console.log(greetUser(newUser));
Output:
Welcome, Alice!
💡 Parameter Best Practices:
- Always specify types for all parameters
- Use descriptive parameter names
- Keep parameter lists short (3-4 parameters max)
- Use object parameters for functions with many arguments
- Consider using type aliases for complex parameter types