TypeScript · Senior · Question 72 of 75
Why are explicit generic constraints better than casting inside a generic function?
function byId<T extends { id: string }>(items: T[], id: string): T | undefined {
return items.find((i) => i.id === id);
}- ✓Correct answer: The constraint lets the compiler verify property access and keeps
Tprecise for callers - 2Casting is faster
- 3Constraints are only documentation
Explanation
Casting ((i as any).id) hides mistakes; the constraint documents and checks the requirement.