Generics: Writing Reusable, Flexible Code

7 min read

Course: TypeScript

Topic: Generics: Writing Reusable, Flexible Code

👋 Welcome Back, Developer!

You have mastered the primitives, you’ve conquered Interfaces, and you’ve tamed Union types. Now, you stand before the concept that separates the TypeScript "users" from the TypeScript "architects": Generics.

If TypeScript were a video game, Generics would be the item crafting system. Instead of finding a specific "Sword of Fire" (a function that only handles strings), you build a blueprint for a "Sword of [Insert Element Here]" (a function that handles whatever you throw at it, safely).

Fun Fact: Generics aren't unique to TypeScript. They were a massive requested feature in languages like C# and Java in the mid-2000s. Before generics, developers had to cast objects blindly, often leading to runtime crashes that felt like stepping on a LEGO in the dark. TypeScript brings this safety to the wild world of JavaScript.

Let's dive in. 🚀


1. The Concept of Generics: Type Variables Explained

The Problem: The "Any" Trap or The "Duplicate" Nightmare

Imagine you need a function that returns whatever you pass into it (an "identity" function).

If you write it for numbers:

typescript
function returnNumber(arg: number): number {
  return arg;
}

Now, your boss asks for the same thing, but for strings.

typescript
function returnString(arg: string): string {
  return arg;
}

This violates the DRY (Don't Repeat Yourself) principle. You might be tempted to use any:

typescript
// 🛑 The "Any" Trap
function returnAnything(arg: any): any {
  return arg;
}

const result = returnAnything("Hello"); 
// TypeScript thinks 'result' is 'any'. We lost our intelligence! 
// result.toUpperrrrCase() // No error shown, but it will crash at runtime.

Using any turns off TypeScript checking. We want the function to accept anything, but we also want TypeScript to remember what specific type we passed in so it can validate the return value.

The Solution: Type Variables

Definition: A Generic is a way to create a component that works over a variety of types rather than a single one. It uses a Type Variable (a special kind of variable that works on types rather than values) to capture the type provided by the user.

We usually use the letter T (stands for Type) as a convention, similar to how we use i in for-loops.

typescript
// ✅ The Generic Solution
function identity<T>(arg: T): T {
  return arg;
}

How to read this:

  1. identity<T>: "I am defining a function named identity, and I'm declaring a type placeholder named T."
  2. (arg: T): "I expect an argument, and its type will be whatever T is."
  3. : T: "I will return something that is the same type as T."

If you pass a string, T becomes string. If you pass a number, T becomes number. It transforms automatically.


2. Creating Generic Functions and Arrow Functions

Now that we understand T, let's look at the syntax for writing these functions. This is the bread and butter of utility libraries (like Lodash) or data fetching hooks.

Standard Function Syntax

When you call a generic function, you can either explicitly say what T is, or let TypeScript infer it (guess it based on the data).

typescript
function echo<T>(item: T): T {
  console.log("Echoing:", item);
  return item;
}

// Option 1: Explicitly defining T (Good for complex types)
const str = echo<string>("TypeScript"); 

// Option 2: Type Inference (The clean, industry standard way)
const num = echo(42); 
// TypeScript looks at 42, realizes T is number.

Arrow Function Syntax

In modern React and clean TS codebases, arrow functions are preferred. The syntax can look a bit alien at first because the generic bracket <T> comes before the parenthesis.

typescript
// Arrow function definition
const getFirstElement = <T>(arr: T[]): T | undefined => {
  return arr[0];
};

const numbers = [1, 2, 3];
const firstNum = getFirstElement(numbers); // T is number

const names = ["Alice", "Bob"];
const firstName = getFirstElement(names); // T is string

⚠️ Important TSX/React Gotcha:
If you are writing this in a .tsx file (React), <T> can be confused with a JSX opening tag (like <div>).
Fix: Add a trailing comma to tell the compiler it's a generic.

typescript
// Inside a .tsx file
const arrowFunc = <T,>(arg: T): T => arg; 

3. Generic Interfaces and Classes

This is where Generics shine in the industry: API Responses.

The Problem

You are fetching data from a backend. The API always wraps the data in a standard envelope:

json
{
  "status": 200,
  "success": true,
  "data": { ...actual data is here... }
}

Sometimes data is a User, sometimes it's a Product, sometimes it's a list of Orders. You don't want to write UserResponse, ProductResponse, and OrderResponse interfaces manually.

The Solution: Generic Interfaces

We create one flexible interface.

typescript
// Define the shape of your actual data models
interface User {
  id: number;
  name: string;
}

interface Product {
  sku: string;
  price: number;
}

// Define a Generic API Response
// T acts as a slot where we plug in our specific model
interface ApiResponse<T> {
  status: number;
  success: boolean;
  data: T; // The magic happens here
}

// Usage
const userResponse: ApiResponse<User> = {
  status: 200,
  success: true,
  data: { id: 1, name: "FreeCodeCamp" } // TS checks this against User interface
};

const productResponse: ApiResponse<Product> = {
  status: 200,
  success: true,
  data: { sku: "TS-101", price: 99.99 } // TS checks this against Product interface
};

This pattern is standard practice in almost every scalable TypeScript project.

Generic Classes

Just like interfaces, classes can handle generic types. This is common for data structures like Queues, Stacks, or State Managers.

typescript
class DataStorage<T> {
  private data: T[] = [];

  addItem(item: T) {
    this.data.push(item);
  }

  getItems(): T[] {
    return [...this.data];
  }
}

// Storage for strings
const textStorage = new DataStorage<string>();
textStorage.addItem("Hello");
// textStorage.addItem(10); // ❌ Error: Argument of type 'number' is not assignable to 'string'.

// Storage for numbers
const numberStorage = new DataStorage<number>();
numberStorage.addItem(100);

4. Adding Constraints to Generics (extends keyword)

The Problem

Sometimes, T is too flexible.
Suppose we want to write a function that logs the .length of the argument.

typescript
function logLength<T>(arg: T): T {
  console.log(arg.length); // ❌ Error! 
  // Property 'length' does not exist on type 'T'.
  return arg;
}

Why the error? TypeScript argues: "Hey, what if T is a number? Numbers don't have a .length property!" TypeScript is right (as usual, annoyingly).

The Solution: Constraints

We need to restrict T so that it allows any type, as long as that type has a .length property. We use the extends keyword.

typescript
// We define an interface describing our constraint
interface Lengthwise {
  length: number;
}

// We tell T: "You can be anything, BUT you must have a .length property"
function logLength<T extends Lengthwise>(arg: T): T {
  console.log(arg.length); // ✅ No error now!
  return arg;
}

// Usage:
logLength("Hello"); // Works (string has .length)
logLength([1, 2, 3]); // Works (array has .length)
logLength({ length: 10, value: "Hi" }); // Works (object has .length)

// logLength(100); // ❌ Error: Argument of type 'number' is not assignable to parameter of type 'Lengthwise'.

Industry Tip: Using keyof with Constraints

A very common pattern is fetching a property from an object safely. You want to make sure you don't ask for a key that doesn't exist.

typescript
function getProperty<T, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}

const developer = { name: "Quincy", lang: "TypeScript" };

getProperty(developer, "name"); // ✅ OK
// getProperty(developer, "age");  // ❌ Error: "age" is not a key of developer

This is heavily used in libraries like Redux or Form handlers to ensure type safety when accessing dynamic properties.


🧠 Summary

  • Generics (<T>) allow you to create reusable code components that work with a variety of types instead of a single one.
  • They solve the problem of code duplication and avoid the unsafe usage of any.
  • You can use them in Functions, Interfaces, and Classes.
  • Constraints (extends) limit what types can be passed into a generic, ensuring the type has specific properties required by your code.

📚 Further Reading & References

Next Up: We will look at Utility Types—TypeScript's built-in toolkit that uses Generics under the hood to make your life easier! Keep coding! 💻

Challenge

Challenge: Implement a Generic groupBy Utility

Your task is to create a generic TypeScript function named groupBy. This function will be a common utility for organizing data.

Requirements:

  1. The function must be named groupBy.
  2. It must accept two generic type parameters. The first, T, represents the type of objects in the array. The second, K, represents a key of T.
  3. You must apply a generic constraint to ensure that K is a valid key of T.
  4. The function must accept two arguments:
    • items: An array of objects of type T.
    • key: A property name of type K to group the items by.
  5. The function should return a new object. The keys of this object will be the values of the property specified by the key argument. The values will be arrays of the original objects (T[]) that share that property value.
  6. The return type should be appropriately typed to reflect this structure, for example, using TypeScript's Record utility type.

Expected result

Your code should be a complete and correct implementation of the groupBy function.

typescript
function groupBy<T extends object, K extends keyof T>(items: T[], key: K): Record<string | number | symbol, T[]> {
  return items.reduce((acc, item) => {
    const groupKey = item[key];
    // The key of a record must be a string, number, or symbol. 
    // We cast groupKey to 'any' to satisfy this, as its specific type is not known at compile time.
    const keyAsString = groupKey as any;
    
    if (!acc[keyAsString]) {
      acc[keyAsString] = [];
    }
    
    acc[keyAsString].push(item);
    return acc;
  }, {} as Record<string | number | symbol, T[]>);
}

A correct solution will:

  • Properly define the generic function with type parameters T and K.
  • Include the constraint K extends keyof T.
  • Implement logic, typically using Array.prototype.reduce or a for...of loop, to iterate through the items array.
  • Correctly access the grouping value for each item using item[key].
  • Build an accumulator object where each key corresponds to a unique value from item[key] and each value is an array of items (T[]) belonging to that group.
  • Return the fully populated accumulator object.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.