TypeScript Functions
Learn how to create and use functions in TypeScript
⚡ What are TypeScript Functions?
Functions in TypeScript are reusable blocks of code that perform specific tasks. TypeScript adds type annotations to function parameters and return values, making your code safer and more predictable.
// Simple function with types
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Alice"));
Output:
Hello, Alice!
Function Types
Named Functions
Standard function declarations
function add(a: number, b: number): number {
return a + b;
}
Function Expressions
Functions assigned to variables
const multiply = function(x: number, y: number): number {
return x * y;
};
Arrow Functions
Concise function syntax
const divide = (a: number, b: number): number => {
return a / b;
};
Anonymous Functions
Functions without names
setTimeout(function() {
console.log("Done!");
}, 1000);
🔹 Basic Function Syntax
A TypeScript function includes parameter types and return type:
// Function with typed parameters and return type
function calculateArea(width: number, height: number): number {
return width * height;
}
const area = calculateArea(5, 10);
console.log(`Area: ${area}`);
Output:
Area: 50
🔹 Function Return Types
Specify what type of value a function returns:
// Returns a string
function getFullName(firstName: string, lastName: string): string {
return `${firstName} ${lastName}`;
}
// Returns a number
function getAge(birthYear: number): number {
return 2024 - birthYear;
}
// Returns nothing (void)
function logMessage(message: string): void {
console.log(message);
}
console.log(getFullName("John", "Doe"));
console.log(getAge(1990));
Output:
John Doe
34
🔹 Function with Multiple Parameters
Functions can accept multiple typed parameters:
function createUser(
name: string,
age: number,
isActive: boolean
): string {
return `User: ${name}, Age: ${age}, Active: ${isActive}`;
}
const user = createUser("Alice", 25, true);
console.log(user);
Output:
User: Alice, Age: 25, Active: true
🔹 Function Type Annotations
You can define function types for variables:
// Define a function type
let mathOperation: (x: number, y: number) => number;
// Assign functions that match the type
mathOperation = function(a: number, b: number): number {
return a + b;
};
console.log(mathOperation(10, 5));
// Reassign with different logic
mathOperation = (a: number, b: number): number => a * b;
console.log(mathOperation(10, 5));
Output:
15
50
💡 Key Points:
- Always specify types for parameters and return values
-
Use
voidwhen a function doesn't return anything - TypeScript infers return types, but explicit types are clearer
- Function types help ensure consistency across your code