Understanding TypeScript Generics
TypeScriptJavaScriptTutorial
What Are Generics?
Generics allow you to write flexible, reusable code while maintaining type safety. Think of them as type parameters for your functions, classes, and interfaces.
Basic Syntax
function identity<T>(arg: T): T {
return arg;
}
const result = identity<string>("hello"); // type is string
const num = identity(42); // type is inferred as number
Generic Constraints
You can constrain generics to only accept certain types:
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(arg: T): T {
console.log(arg.length);
return arg;
}
logLength("hello"); // OK
logLength([1, 2, 3]); // OK
logLength(42); // Error: number doesn't have length
Generic Interfaces
interface Repository<T> {
find(id: string): Promise<T>;
findAll(): Promise<T[]>;
create(item: T): Promise<T>;
update(id: string, item: Partial<T>): Promise<T>;
delete(id: string): Promise<void>;
}
Real-World Example: API Client
async function fetchData<T>(url: string): Promise<T> {
const res = await fetch(url);
if (!res.ok) throw new Error("Failed to fetch");
return res.json() as Promise<T>;
}
interface User {
id: string;
name: string;
email: string;
}
const user = await fetchData<User>("/api/users/1");
Conclusion
Generics are one of TypeScript's most powerful features. Master them and you'll write more flexible, reusable, and type-safe code.