TypeScript Generics for Reusable Code

📌 Topic: TypeScript Generics — the feature that makes your code truly reusable Most devs use TypeScript to add types. Few use it to write code that is flexible AND fully type-safe at the same time. That's exactly what Generics give you. Without Generics, you end up doing this: 🚫 Any kills all type safety function getFirstItem(arr: any[]): any { return arr[0]; } const num = getFirstItem([1, 2, 3]); // type: any ❌ const str = getFirstItem(['a', 'b']); // type: any ❌ With Generics: ✅ Type flows through — no any, no casting function getFirstItem<T>(arr: T[]): T { return arr[0]; } const num = getFirstItem([1, 2, 3]); // type: number ✅ const str = getFirstItem(['a', 'b']); // type: string ✅ Real-world usage — Generic API response wrapper: interface ApiResponse<T> { data: T; status: number; message: string; } // Reuse across your entire app type UserResponse = ApiResponse<User>; type ProductResponse = ApiResponse<Product>; type OrderResponse = ApiResponse<Order[]>; One interface. Infinite reuse. Zero repetition. Constrained Generics — when T shouldn't be just anything: T must have an 'id' property function findById<T extends { id: number }>(items: T[], id: number): T | undefined { return items.find(item => item.id === id); } findById(users, 1); // ✅ works — User has id findById(products, 5); // ✅ works — Product has id findById([1, 2, 3], 1); // ❌ compile error — number has no id Generic utility types TypeScript ships out of the box: Partial<T> → makes all properties optional Required<T> → makes all properties required Readonly<T> → prevents mutation Pick<T, K> → extract only the keys you need Omit<T, K> → exclude keys you don't want Record<K, V> → build key-value map types The difference between a codebase with Generics and one without is simple: Without Generics → duplicate types everywhere, any sprinkled around, runtime errors TypeScript should have caught With Generics → one source of truth, full type safety, errors caught at compile time not in production If you're writing TypeScript without Generics — you're using 40% of the language. 💡 Which utility type do you reach for the most? 👇 #TypeScript #JavaScript #FullStackDev #WebDevelopment #SoftwareEngineering #Angular #React #CleanCode

To view or add a comment, sign in

Explore content categories