</>
linuxideas
< devops/tutorial
$cat ~/articles/devops/tutorial/understanding-typescript-generics.md

Understanding TypeScript Generics

A practical guide to TypeScript generics — from basic syntax to advanced patterns used in real codebases.

K
Kartik Gupta
Author
April 5, 2026
Published
1 min read
Read time

The Problem

Without generics, you'd have to choose between:

  1. No type safety — using any
  2. No reusability — writing separate functions for each type
typescript
// Bad: no type safety
function identity(value: any): any {
  return value;
}

// Good: type-safe AND reusable
function identity<T>(value: T): T {
  return value;
}

Generic Constraints

You can constrain generics using extends:

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

Real-World Example

Here's a generic API response wrapper:

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

async function fetchUser(): Promise<ApiResponse<User>> {
  const response = await fetch('/api/user');
  return response.json();
}

Key Takeaways

  • Generics let you write flexible, reusable code without sacrificing type safety
  • Use extends to constrain what types are allowed
  • Constraints like keyof enable powerful utility patterns

Generics take practice — try refactoring some of your existing code to use them.

$ share --article