Function typing is crucial for building reliable APIs. It ensures your functions receive the right data and return the expected results.
Why type functions?
- Prevents bugs - TypeScript catches errors when you pass wrong data types
- Self-documenting - Anyone reading your code knows what the function expeTypeScript Interface Practicects
- Better autocomplete - Your editor knows what parameters to suggest
- API reliability - Ensures your endpoints handle data correctly
Function signature:
function functionName(parameter: type): returnType {
// function body
}
Examples:
// Simple function with typed parameters and return type
function calculateTotal(price: number, quantity: number): number {
return price * quantity;
}
// Function that returns a user object
function getUserById(id: number): User {
// In real code, this would fetch from database
return {
id: id,
name: "Test User",
email: "test@example.com",
createdAt: new Date(),
};
}
// Function that can return multiple types
function findUserById(id: string | number): User | null {
// Returns User if found, null if not found
// Can accept either string or number ID
return null; // Simplified for example
}
// Function with no return value (void)
function logUser(user: User): void {
console.log(`User: ${user.name} (${user.email})`);
}