ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

TypeScript Tutorial• 8 min read

Generics: Reusable, Type-Safe Components & Functions

Writing flexible data structures with type parameters and generic constraints

Generics allow you to write reusable functions, interfaces, and classes that work across a variety of types while preserving full compile-time type safety instead of falling back to any.

Type Parameters and Constraints

The <T> syntax represents a type variable (or type placeholder) captured when the function is invoked.

Generic constraints: Restrict acceptable types using extends (e.g., <T extends { length: number }> ensures T always has a .length property).

keyof: Generates a union of property keys, allowing you to create type-safe property access functions like <T, K extends keyof T>.

Generic Repository and Property Accessor
// Generic API Response Wrapper
interface ApiResponse<T> {
  data: T;
  status: number;
  timestamp: string;
}

// Generic property getter ensuring property key actually exists on object
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const product = { id: 401, name: "Mechanical Keyboard", price: 149 };

// Type of productPrice is inferred as number
const productPrice = getProperty(product, "price");

// This would trigger a compile error:
// getProperty(product, "nonExistentKey");

console.log(`Price: $${productPrice}`);
keyof T guarantees that invalid property names are caught by the compiler.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What does the constraint <T extends { id: string }>() guarantee about the generic parameter T?