Books/TypeScript Essentials/Functions and Their Types

    Functions and Their Types

    Functions and Their Types

    Functions are the workhorses of any application. When AI generates code, functions make up the bulk of the logic. Understanding how TypeScript types them helps you read, review, and prompt for better code.

    Basic Function Types

    Every function has input types (parameters) and an output type (return value):

    function add(a: number, b: number): number {
      return a + b;
    }
    //         ↑ params        ↑ return type

    Reading this: "add takes two numbers and returns a number."

    Arrow Functions

    Modern JavaScript (and AI-generated code) uses arrow functions frequently:

    // Regular function
    function greet(name: string): string {
      return `Hello, ${name}!`;
    }
    
    // Arrow function — same thing, shorter syntax
    const greet = (name: string): string => {
      return `Hello, ${name}!`;
    };
    
    // Even shorter — implicit return for one-liners
    const greet = (name: string): string => `Hello, ${name}!`;

    All three do exactly the same thing. AI tools often use arrow functions because they're more concise.

    What to ask your AI: "Can you rewrite this arrow function as a regular function so I can understand it better?"

    Optional and Default Parameters

    // Optional parameter — might not be provided
    function greet(name: string, greeting?: string): string {
      return `${greeting || "Hello"}, ${name}!`;
    }
    
    greet("Alice");           // "Hello, Alice!"
    greet("Alice", "Hey");    // "Hey, Alice!"
    
    // Default parameter — has a fallback value
    function greet(name: string, greeting: string = "Hello"): string {
      return `${greeting}, ${name}!`;
    }
    
    greet("Alice");           // "Hello, Alice!"
    greet("Alice", "Hey");    // "Hey, Alice!"

    The difference: ? makes it optional (could be undefined), while = "Hello" provides a default value.

    Callback Functions

    A callback is a function passed as an argument to another function. You'll see these constantly:

    // A function that takes a callback
    function fetchData(url: string, onSuccess: (data: string) => void): void {
      // ... fetch data, then call onSuccess with the result
    }
    
    // Using it
    fetchData("https://api.example.com", (data) => {
      console.log(data);
    });

    Reading the type (data: string) => void:

    • Takes one parameter: data which is a string
    • Returns nothing (void)

    Common Callback Patterns

    // Event handler — takes an event, returns nothing
    type ClickHandler = (event: MouseEvent) => void;
    
    // Filter function — takes an item, returns true/false
    type FilterFn = (item: string) => boolean;
    
    // Transform function — takes a value, returns a new value
    type MapFn = (value: number) => number;

    What to ask your AI: "I see this callback type: [paste it]. When does this function get called and what does it receive?"

    Async Functions and Promises

    Most real apps fetch data from APIs. This requires async/await and Promises:

    // An async function returns a Promise
    async function getUser(id: number): Promise<User> {
      const response = await fetch(`/api/users/${id}`);
      const data = await response.json();
      return data;
    }
    
    // Using it
    const user = await getUser(1);
    console.log(user.name); // TypeScript knows 'user' is a User

    Reading Promise<User>:

    • This function is async — it doesn't return immediately
    • When it's done, it returns a User object
    • You use await to wait for the result

    You'll see Promise<something> in almost every function that:

    • Fetches data from an API
    • Reads from a database
    • Does any operation that takes time

    What to ask your AI: "This function returns Promise<User[]>. Can you explain the async flow and where the data comes from?"

    Generics — The <T> You Keep Seeing

    Generics let functions work with multiple types. You'll see <T> a lot:

    // A function that works with ANY type
    function getFirst<T>(items: T[]): T {
      return items[0];
    }
    
    getFirst<string>(["a", "b", "c"]);  // Returns "a" (type: string)
    getFirst<number>([1, 2, 3]);        // Returns 1 (type: number)
    
    // TypeScript usually infers the type, so you'll see:
    getFirst(["a", "b", "c"]);  // Still knows it returns a string

    Think of <T> as a type variable — a placeholder that gets filled in when you use the function.

    Common Generics You'll See

    // API response wrapper
    async function fetchApi<T>(url: string): Promise<T> {
      const response = await fetch(url);
      return response.json();
    }
    
    // Usage — T becomes User
    const user = await fetchApi<User>("/api/users/1");
    
    // Usage — T becomes Product[]
    const products = await fetchApi<Product[]>("/api/products");

    You don't need to write generics yourself. Just recognize them when AI generates them. The key insight: <T> means "this works with different types."

    What to ask your AI: "I see <T> in this function. Can you explain what type T becomes when this function is actually called?"

    Function Overloads (Advanced)

    Sometimes you'll see multiple function signatures. This is a function overload:

    function format(value: string): string;
    function format(value: number): string;
    function format(value: string | number): string {
      return String(value);
    }

    This tells TypeScript: "this function accepts either a string or a number, and always returns a string." Don't worry about writing these — just recognize the pattern.

    Real-World Patterns from AI Code

    Here are functions you'll actually see:

    API Service Function

    async function createUser(userData: {
      name: string;
      email: string;
      password: string;
    }): Promise<User> {
      const response = await fetch("/api/users", {
        method: "POST",
        body: JSON.stringify(userData),
      });
      return response.json();
    }

    Event Handler

    const handleSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
      event.preventDefault();
      // process form...
    };

    Utility / Helper Function

    const formatPrice = (cents: number): string => {
      return `$${(cents / 100).toFixed(2)}`;
    };
    
    formatPrice(1999); // "$19.99"

    Array Processing

    const getActiveUsers = (users: User[]): User[] => {
      return users.filter((user) => user.isActive);
    };

    Reading Functions Checklist

    When you encounter a function in AI-generated code:

    1. What are the parameters? Check the names and types inside ( )
    2. What does it return? Look after the ) — the : ReturnType
    3. Is it async? Look for async keyword and Promise<> return type
    4. Does it use generics? Look for <T> or similar
    5. Is it a callback? Look for () => type syntax in parameters

    What to ask your AI: "Walk me through this function step by step. What does it take in, what does it do, and what does it return?"

    What's Next?

    You understand types, interfaces, and functions — the core of TypeScript. The next tutorial covers TypeScript for Frontend (React) — how these concepts come together in React components.


    🌐 www.genai-mentor.ai