Common Function Patterns

Loading concept...

Common Function Patterns in TypeScript

The Magic of Function Recipes 🍳

Imagine you’re a chef. Every dish you make follows a recipe. Some recipes are quick (like making toast), some need you to wait (like baking a cake), and some need a helper to do part of the work (like asking someone to chop vegetables).

TypeScript functions work the same way! They are recipes that tell your computer exactly what ingredients go in and what comes out.


1. Arrow Function Typing

What Is It?

An arrow function is like a shortcut recipe. Instead of writing a long instruction, you write it in one quick line.

Simple Example:

// Regular function (long way)
function add(a: number, b: number): number {
  return a + b;
}

// Arrow function (shortcut!)
const add = (a: number, b: number): number => {
  return a + b;
};

Why Use Arrows?

Think of arrows like text shortcuts on your phone. Instead of typing “be right back,” you type “brb.” Same message, less writing!

The Anatomy of an Arrow Function

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

Let’s break it down:

  1. name: string → The ingredient (must be text)
  2. : string after () → What comes out (also text)
  3. => → The magic arrow!

Even Shorter!

When you have just ONE line, skip the curly braces:

// Super short version
const double = (n: number): number => n * 2;

// Same as writing:
const double = (n: number): number => {
  return n * 2;
};

Storing Arrow Functions as Types

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

// Use it!
const multiply: MathOperation = (a, b) => a * b;
const divide: MathOperation = (a, b) => a / b;

This is like saying: “Every MathOperation recipe takes 2 numbers and gives back 1 number.”


2. Callback Typing

What Is It?

A callback is like asking a friend to help you cook. You give them instructions, and they do part of the work for you.

Real Life Example:

  • You say: “When the timer goes off, take the pizza out”
  • Your friend follows your instruction later

Simple Callback Example

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

// The callback is the function inside map()
const doubled = numbers.map((n: number): number => {
  return n * 2;
});

// Result: [2, 4, 6, 8, 10]

Here, map() calls your little arrow function for each number!

Creating Your Own Callback Function

// Step 1: Define what the callback looks like
type GreetCallback = (message: string) => void;

// Step 2: Create a function that uses a callback
function processUser(
  name: string,
  callback: GreetCallback
): void {
  const message = `Welcome, ${name}!`;
  callback(message); // Run the callback!
}

// Step 3: Use it!
processUser("Alex", (msg) => {
  console.log(msg); // "Welcome, Alex!"
});

Why void?

void means “this function doesn’t give anything back.” It just does something (like printing to the screen).

// Returns nothing (void)
const sayHi = (name: string): void => {
  console.log(`Hi, ${name}!`);
};

// Returns a string
const getGreeting = (name: string): string => {
  return `Hi, ${name}!`;
};

Common Callback Patterns

// Event callback (like clicking a button)
type ClickHandler = (event: MouseEvent) => void;

// Filter callback (decides yes or no)
type FilterFn = (item: number) => boolean;

// Transform callback (changes something)
type MapFn<T, U> = (item: T) => U;

3. Async Function Typing

What Is It?

An async function is like ordering pizza for delivery. You place the order, then wait for it to arrive. You don’t stand at the door the whole time—you do other things!

The Promise

When you order pizza, you get a promise: “Your pizza will arrive!” In TypeScript, async functions return a Promise.

// This function PROMISES to give you a string
const fetchName = async (): Promise<string> => {
  return "Alex";
};

The await Keyword

await means “wait here until the pizza arrives.”

const getUserData = async (): Promise<string> => {
  // Pretend this takes time (like fetching from internet)
  const name = await fetchName();
  return `Got user: ${name}`;
};

Full Async Example

// Define what user data looks like
interface User {
  id: number;
  name: string;
}

// Async function that fetches a user
const getUser = async (id: number): Promise<User> => {
  // Simulate waiting for data
  const user: User = {
    id: id,
    name: "Alex"
  };
  return user;
};

// Using it
const showUser = async (): Promise<void> => {
  const user = await getUser(1);
  console.log(user.name); // "Alex"
};

Error Handling with Try/Catch

Sometimes the pizza shop is closed! Handle errors gracefully:

const safeFetch = async (): Promise<string> => {
  try {
    const data = await fetchData();
    return data;
  } catch (error) {
    return "Something went wrong!";
  }
};

Promise vs Async/Await

They do the same thing, just written differently:

// Promise way (older style)
function getData(): Promise<string> {
  return fetch("/api/data")
    .then(response => response.text());
}

// Async/await way (easier to read!)
async function getData(): Promise<string> {
  const response = await fetch("/api/data");
  return response.text();
}

Putting It All Together

Here’s a real-world example using ALL three patterns:

// 1. Arrow function type
type ProcessFn = (data: string) => string;

// 2. Callback in action
const processItems = (
  items: string[],
  processor: ProcessFn
): string[] => {
  return items.map(processor);
};

// 3. Async function bringing it together
const loadAndProcess = async (): Promise<string[]> => {
  // Pretend we fetch data
  const items = ["apple", "banana", "cherry"];

  // Process with a callback
  const result = processItems(
    items,
    (item) => item.toUpperCase()
  );

  return result;
  // Returns: ["APPLE", "BANANA", "CHERRY"]
};

Quick Summary

graph TD A[Function Patterns] --> B[Arrow Functions] A --> C[Callbacks] A --> D[Async Functions] B --> E["const fn = #40;x: T#41;: R => ..."] C --> F["fn#40;callback: #40;#41; => void#41;"] D --> G["async fn#40;#41;: Promise<T>"]
Pattern When to Use Returns
Arrow Quick, inline functions Any type
Callback Pass function as argument Usually void
Async Wait for something Promise<T>

You’ve Got This! 🎉

Remember:

  • Arrow functions = Shortcuts for writing functions
  • Callbacks = Functions you pass to other functions
  • Async functions = Functions that wait for something

You’re now ready to write beautiful, type-safe functions in TypeScript!

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.