TypeScript
900
TypeScript Generics: A Practical Guide
A
Administrator
December 1, 2025
What are Generics?
Generics allow you to write flexible, reusable code that works with multiple types while maintaining type safety.
Basic Generic Function
function identity<T>(arg: T): T {
return arg;
}
const result1 = identity<string>("Hello");
const result2 = identity<number>(42);
Generic Interfaces
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
interface User {
id: number;
name: string;
}
const response: ApiResponse<User> = {
data: { id: 1, name: "John" },
status: 200,
message: "Success"
};
Generic Constraints
Restrict generics to specific types:
interface HasLength {
length: number;
}
function logLength<T extends HasLength>(arg: T): void {
console.log(arg.length);
}
logLength("Hello"); // Works
logLength([1, 2, 3]); // Works
// logLength(123); // Error: number doesn't have length
Generic Classes
class DataStore<T> {
private data: T[] = [];
add(item: T): void {
this.data.push(item);
}
get(index: number): T | undefined {
return this.data[index];
}
}
const numberStore = new DataStore<number>();
numberStore.add(42);
Best Practices
- Use meaningful generic parameter names (T for Type, K for Key, V for Value)
- Apply constraints when necessary to ensure type safety
- Keep generics simple and don't over-engineer
- Use default generic types when appropriate
Comments (0)
No comments yet. Be the first to comment!
A
About Administrator
Default admin user