TypeScript
Programming

Mastering TypeScript Generics: A Practical Guide

Jackson MwangiNovember 28, 20246 min read

Mastering TypeScript Generics

Generics are one of the most powerful features in TypeScript. Let me show you how to use them effectively.

What Are Generics?

Generics allow you to write flexible, reusable code while maintaining type safety. Think of them as "type variables."

// Without generics - loses type information
function identity(arg: any): any {
  return arg;
}

// With generics - preserves type
function identity<T>(arg: T): T {
  return arg;
}

const result = identity<string>("hello"); // result is string
const num = identity(42); // TypeScript infers number

Practical Patterns

1. Generic Constraints

interface HasLength {
  length: number;
}

function logLength<T extends HasLength>(arg: T): T {
  console.log(arg.length);
  return arg;
}

logLength("hello"); // ✓ strings have length
logLength([1, 2, 3]); // ✓ arrays have length
logLength(123); // ✗ numbers don't have length

2. Generic React Components

interface ListProps<T> {
  items: T[];
  renderItem: (item: T) => React.ReactNode;
}

function List<T>({ items, renderItem }: ListProps<T>) {
  return <ul>{items.map(renderItem)}</ul>;
}

// Usage
<List 
  items={users} 
  renderItem={(user) => <li key={user.id}>{user.name}</li>} 
/>

3. Utility Types

// Pick specific properties
type UserPreview = Pick<User, 'id' | 'name'>;

// Make all properties optional
type PartialUser = Partial<User>;

// Make all properties required
type RequiredUser = Required<User>;

Conclusion

Generics might seem complex at first, but they're essential for writing professional TypeScript code. Start with simple use cases and gradually adopt more advanced patterns.

Enjoyed this article?

Let's connect and discuss more about software development.