TypeScript Arrow Functions

Write concise and modern function syntax

➡️ What are Arrow Functions?

Arrow functions provide a shorter syntax for writing functions in TypeScript. They use the => arrow notation and offer cleaner code, especially for simple operations and callbacks, while maintaining full type safety.


// Traditional function
function add(a: number, b: number): number {
    return a + b;
}

// Arrow function
const addArrow = (a: number, b: number): number => a + b;

console.log(addArrow(5, 3));
                                    

Output:

8

Arrow Function Features

Concise Syntax

Shorter function declarations

const square = (x: number) => x * x;
🔙

Implicit Return

No return keyword needed

const greet = (name: string) => 
    `Hello, ${name}!`;
🎯

Lexical This

Inherits this from parent scope

// No binding issues
setTimeout(() => {
    console.log(this);
}, 1000);
📝

Type Annotations

Full TypeScript support

const calc = (
    a: number, 
    b: number
): number => a + b;

🔹 Basic Arrow Function Syntax

Different ways to write arrow functions:

// Single parameter (parentheses optional)
const double = (x: number): number => x * 2;

// Multiple parameters (parentheses required)
const add = (a: number, b: number): number => a + b;

// No parameters
const greet = (): string => "Hello!";

// Multiple statements (curly braces required)
const calculate = (x: number, y: number): number => {
    const sum = x + y;
    return sum * 2;
};

console.log(double(5));
console.log(add(3, 7));
console.log(greet());
console.log(calculate(4, 6));

Output:

10

10

Hello!

20

🔹 Arrow Functions with Arrays

Perfect for array methods like map, filter, and reduce:

const numbers: number[] = [1, 2, 3, 4, 5];

// Map with arrow function
const doubled = numbers.map((num: number) => num * 2);

// Filter with arrow function
const evens = numbers.filter((num: number) => num % 2 === 0);

// Reduce with arrow function
const sum = numbers.reduce((total: number, num: number) => total + num, 0);

console.log("Doubled:", doubled);
console.log("Evens:", evens);
console.log("Sum:", sum);

Output:

Doubled: [2, 4, 6, 8, 10]

Evens: [2, 4]

Sum: 15

🔹 Arrow Functions Returning Objects

Wrap object literals in parentheses:

// Wrap object in parentheses for implicit return
const createUser = (name: string, age: number) => ({
    name: name,
    age: age,
    isActive: true
});

// Shorthand property syntax
const createPerson = (name: string, age: number) => ({ name, age });

console.log(createUser("Alice", 25));
console.log(createPerson("Bob", 30));

Output:

{ name: 'Alice', age: 25, isActive: true }

{ name: 'Bob', age: 30 }

🔹 Arrow Functions with Type Aliases

Define function types for better reusability:

// Define function type
type MathOperation = (a: number, b: number) => number;

// Use the type
const multiply: MathOperation = (a, b) => a * b;
const divide: MathOperation = (a, b) => a / b;
const subtract: MathOperation = (a, b) => a - b;

console.log("Multiply:", multiply(6, 3));
console.log("Divide:", divide(15, 3));
console.log("Subtract:", subtract(10, 4));

Output:

Multiply: 18

Divide: 5

Subtract: 6

🔹 Arrow Functions with Optional Parameters

Combine arrow functions with optional and default parameters:

// Optional parameter
const greetUser = (name: string, greeting?: string): string => 
    `${greeting || "Hello"}, ${name}!`;

// Default parameter
const calculateDiscount = (price: number, discount: number = 0.1): number => 
    price - (price * discount);

console.log(greetUser("Alice"));
console.log(greetUser("Bob", "Welcome"));
console.log("Price:", calculateDiscount(100));
console.log("Price with 20% off:", calculateDiscount(100, 0.2));

Output:

Hello, Alice!

Welcome, Bob!

Price: 90

Price with 20% off: 80

🔹 Practical Example: Data Processing

Use arrow functions for data transformation:

type Product = {
    name: string;
    price: number;
    inStock: boolean;
};

const products: Product[] = [
    { name: "Laptop", price: 999, inStock: true },
    { name: "Mouse", price: 25, inStock: false },
    { name: "Keyboard", price: 75, inStock: true }
];

// Get available products
const available = products.filter(p => p.inStock);

// Get product names
const names = available.map(p => p.name);

// Calculate total value
const total = available.reduce((sum, p) => sum + p.price, 0);

console.log("Available:", names);
console.log("Total value:", total);

Output:

Available: ['Laptop', 'Keyboard']

Total value: 1074

💡 Arrow Function Tips:

  • Use arrow functions for short, simple operations
  • Omit curly braces for single-expression functions
  • Wrap object returns in parentheses: () => ({ key: value })
  • Arrow functions don't have their own this binding
  • Can't be used as constructors (no new keyword)

🧠 Test Your Knowledge

What symbol is used to define an arrow function?