Generic type constraints applied
Why it matters
An unconstrained generic <T> is effectively <T extends unknown> — it accepts any value, and TypeScript cannot enforce meaningful relationships between T and the function's behavior. The symptom is forced casts inside the generic body: if you need (item as any).id, the generic is not constrained correctly. ISO 25010:2011 §6.5.4 classifies this as a type-safety defect. Unconstrained generics in utility code are particularly insidious because they look safe from the outside while silently bypassing type checks inside.
Severity rationale
Medium because unconstrained generics defeat the purpose of generic typing — they provide an API that looks type-safe but requires internal casts to work, masking real type errors.
Remediation
Add extends constraints to generics that access specific properties or operate on values with known shapes. This eliminates the internal casts that unconstrained generics require:
// Bad: unconstrained T, forced cast to access 'id'
function findById<T>(items: T[], id: string): T | undefined {
return items.find((item) => (item as any).id === id)
}
// Good: constraint ensures T has 'id'
function findById<T extends { id: string }>(items: T[], id: string): T | undefined {
return items.find((item) => item.id === id) // no cast needed
}
// Good: keyof constraint for property access
function getProperty<T extends object, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key]
}
DetectionPro
The detection method for this pattern is part of AuditBuffet Pro.
The full method (what to look for, pass and fail conditions, and how results get reported) ships inside the Code Quality Essentials Audit. The pattern definition, severity rationale, and remediation remain openly licensed under CC-BY-4.0.
External references
- iso-25010:2011 · maintainability.modifiability — Maintainability — Modifiability
Taxons
History
- 2026-04-18·v1.0.0·Initial import from code-quality-essentials·automated