Page cover
Generics transform rigid code into flexible solutions -
maintaining type safety,
enabling reusability &
unlocking elegant patterns.

TypeScript Generics: Practical Use Cases

TypeScript Generics: Practical Use Cases
TypeScript December 5, 2024 10 min read

Explore real-world scenarios where TypeScript generics solve common problems and make your code more reusable and type-safe.

Prerequisites

Essential knowledge and skills you should have before starting

Basic TypeScript knowledge (types, interfaces)
Understanding of JavaScript ES6+ features

TypeScript generics allow you to write reusable, type-safe code. Instead of working with the 'any' type, generics let you preserve type information while keeping your code flexible.

Basic Generic Function

typescript
// Without generics - loses type information
function getFirstItem(arr: any[]): any {
  return arr[0];
}

// With generics - preserves type information
function getFirstItem<T>(arr: T[]): T {
  return arr[0];
}

const numbers = [1, 2, 3];
const first = getFirstItem(numbers); // TypeScript knows this is a number

const strings = ['a', 'b', 'c'];
const firstStr = getFirstItem(strings); // TypeScript knows this is a string

Generic API Response Handler

typescript
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
  const response = await fetch(url);
  const json = await response.json();
  return {
    data: json.data,
    status: response.status,
    message: json.message
  };
}

// Usage with specific types
interface User {
  id: number;
  name: string;
}

const userResponse = await fetchData<User>('/api/user/1');
// userResponse.data is typed as User

Generic Data Store

typescript
class DataStore<T> {
  private items: Map<string, T> = new Map();

  set(key: string, value: T): void {
    this.items.set(key, value);
  }

  get(key: string): T | undefined {
    return this.items.get(key);
  }

  getAll(): T[] {
    return Array.from(this.items.values());
  }
}

// Type-safe stores for different entities
const userStore = new DataStore<User>();
const productStore = new DataStore<Product>();

userStore.set('user1', { id: 1, name: 'John' });
const user = userStore.get('user1'); // Typed as User | undefined

Generics are essential for building reusable, type-safe abstractions in TypeScript. They enable you to write code once and use it with multiple types while maintaining full type safety.

Tags: TypeScript Generics Type Safety

Found this helpful?

I write about software engineering, architecture, and best practices. Check out more articles or get in touch.