All articles
TypeScriptTypeScriptJavaScript

TypeScript Generics: A Practical Guide

Learn how to leverage TypeScript generics to write reusable, type-safe code for any situation.

Apr 26, 20268 min read9,800 views1204 words

TypeScript Generics: A Practical Guide

Generics allow you to write reusable, type-safe code that works with any type.

Basic Generic Functions

TS
1function identity<T>(arg: T): T {
2 return arg;
3}
4 
5const result = identity<string>('hello');
6const num = identity<number>(42);

Generic Constraints

You can constrain what types are allowed:

TS
1interface HasLength {
2 length: number;
3}
4 
5function logLength<T extends HasLength>(arg: T): T {
6 console.log(arg.length);
7 return arg;
8}

Think of generics as type variables — they hold types the way regular variables hold values.

Real-World Example: API Response Wrapper

TS
1interface ApiResponse<T> {
2 data: T;
3 error: string | null;
4 status: number;
5}
6 
7async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
8 const res = await fetch(url);
9 const data = await res.json();
10 return { data, error: null, status: res.status };
11}