Understanding TypeScript Generics with Real Examples

Understanding TypeScript Generics with Real Examples

Generics are one of TypeScript's most powerful features. This post walks through real-world use cases that make the concept click.

April 30, 2026·5 min read
Share

What Are Generics?

Generics allow you to write functions and types that work with any type while preserving type safety. Think of them as type placeholders.

A Simple Example

function identity<T>(value: T): T {
  return value;
}

const result = identity("hello"); // string
const num = identity(42);         // number

Practical: API Response Wrapper

interface ApiResponse<T> {
  data: T;
  error: string | null;
  status: number;
}

async function fetchPost(slug: string): Promise<ApiResponse<Post>> {
  // ...
}

Constrained Generics

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

getProperty({ name: "Hoa", age: 25 }, "name"); // ✅
getProperty({ name: "Hoa" }, "phone");          // ❌ Error