GenericsBeginner
1Question 1 of 2
typescriptHow do Generics work in TypeScript and how do you constrain generic types?
Explanation & Concept
Generics allow writing flexible, reusable code components that work over a variety of types rather than a single one, while maintaining compile-time type safety.
You constrain generic types using the `extends` keyword, ensuring the generic argument possesses specific properties.
Code Example
typescript
// Generic constraint: T must have an 'id' property
interface HasId {
id: string | number;
}
function findById<T extends HasId>(items: T[], targetId: string | number): T | undefined {
return items.find((item) => item.id === targetId);
}
interface Product {
id: number;
title: string;
price: number;
}
const inventory: Product[] = [{ id: 101, title: "Laptop", price: 999 }];
const item = findById(inventory, 101);
console.log(item?.title); // Fully typed as Product!How It Works & Key Takeaways
The generic `<T extends HasId>` guarantees that `findById` can access `item.id`, while returning the exact input type `Product` rather than losing type specificity.