Courses/TypeScript/Functions and Generics

    Lesson 4 • Intermediate

    Functions and Generics 🔧

    Type your function parameters, return values, and overloads — then write flexible, reusable code with generics that work with any type.

    What You'll Learn in This Lesson

    • • Type function parameters, return values, and rest parameters
    • • Optional parameters, defaults, and function overloads
    • • Generics: <T> syntax, constraints, and keyof
    • • Generic interfaces, classes, and the Result pattern
    • • Real-world patterns: ApiResponse<T>, Stack<T>

    1️⃣ Typed Functions

    TypeScript lets you annotate function parameters and return types, giving you compile-time safety for every function call. Optional parameters use ? and function overloads let you define multiple call signatures.

    Try It: Typed Functions

    Parameters, returns, optionals, rest params, and overloads

    Try it Yourself »
    JavaScript
    // Typed Functions in TypeScript
    console.log("=== Function Parameter & Return Types ===");
    console.log();
    
    // Basic typed function
    console.log("function add(a: number, b: number): number {");
    console.log("  return a + b;");
    console.log("}");
    
    function add(a, b) { return a + b; }
    console.log("add(5, 3) = " + add(5, 3));
    console.log();
    
    // Optional parameters
    console.log("=== Optional Parameters ===");
    function greet(name, greeting) {
      greeting = greeting || "Hello";
      return greeting + ", " + na
    ...

    2️⃣ Generics

    Generics let you write functions, interfaces, and classes that work with any type while preserving type safety. The <T> is a type variable that gets filled in when you call the function.

    Try It: Generics

    Generic functions, constraints, keyof, and multiple type params

    Try it Yourself »
    JavaScript
    // Generics — Write Once, Use with Any Type
    console.log("=== Why Generics? ===");
    console.log();
    
    // Without generics — you lose type info
    console.log("// WITHOUT generics:");
    console.log("function firstItem(arr: any[]): any { return arr[0]; }");
    console.log("// Returns 'any' — you lose all type information!");
    console.log();
    
    // With generics — type preserved
    console.log("// WITH generics:");
    console.log("function firstItem<T>(arr: T[]): T { return arr[0]; }");
    console.log("firstItem([1,2,3])  
    ...

    3️⃣ Generic Patterns

    Generics shine in real-world patterns like API response wrappers, data structures, and the Result type for error handling.

    Try It: Generic Patterns

    ApiResponse<T>, Stack<T>, and Result<T, E>

    Try it Yourself »
    JavaScript
    // Generic Interfaces, Classes, and Real-World Patterns
    console.log("=== Generic Interfaces ===");
    console.log();
    console.log("interface ApiResponse<T> {");
    console.log("  data: T;");
    console.log("  status: number;");
    console.log("  message: string;");
    console.log("}");
    console.log();
    
    let userResponse = { data: { id: 1, name: "Alice" }, status: 200, message: "OK" };
    let postsResponse = { data: [{ id: 1, title: "Hello" }], status: 200, message: "OK" };
    console.log("ApiResponse<User>:   " + JSON.
    ...

    ⚠️ Common Mistakes

    ⚠️
    Over-constraining generics — Don't add unnecessary constraints. If your function only needs .length, constrain to { length: number } not string.
    ⚠️
    Unnecessary generics — If T is only used once, you don't need a generic. Use the concrete type instead.
    💡
    Pro Tip: Name generics meaningfully: TData, TError, TKey instead of just T, U, V.

    📋 Quick Reference

    PatternSyntax
    Typed function(a: number): string
    Optional param(name?: string)
    Generic funcfunction f<T>(x: T): T
    Constraint<T extends HasLength>
    keyof<K extends keyof T>
    Generic interfaceinterface Box<T> { val: T }

    🎉 Lesson Complete!

    You've mastered typed functions and generics! Next, explore classes and OOP in TypeScript.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service