# Generics in TypeScript Explained
Generics let you write functions and types that work with multiple types while still keeping full type safety — instead of choosing between rigid single-type code or unsafe `any`.
## The Problem Without Generics
```typescript
function firstItem(arr: any[]): any {
return arr[0];
}
```
This works for any array, but you lose all type information — the return value is typed `any`, so TypeScript can't help you afterward.
## The Generic Version
```typescript
function firstItem(arr: T[]): T {
return arr[0];
}
const num = firstItem([1, 2, 3]); // inferred as number
const name = firstItem(["Aarav", "Priya"]); // inferred as string
```
`T` is a placeholder type, filled in based on what's actually passed — full type safety without writing separate functions per type.
## Generic Interfaces
```typescript
interface ApiResponse {
data: T;
success: boolean;
}
const response: ApiResponse = { data: student, success: true };
```
This pattern is extremely common for typing API responses, since the response shape is consistent but the `data` type changes per endpoint.
## Constraints
Generics can be restricted to types with specific properties:
```typescript
function getLength(item: T): number {
return item.length;
}
```
## Where You'll See Generics
React's `useState`, array methods, and most API client libraries rely heavily on generics — even if you never write your own, you'll use them constantly.
## Conclusion
Generics aren't about making code more abstract for its own sake — they exist to avoid duplicating logic while keeping type safety intact.
Back to Blogs
Generics in TypeScript Explained
What generics actually solve in TypeScript, explained with practical examples instead of abstract theory.
07 Aug 2026
6 min read