patterntypescriptModeratepending
TypeScript generic constraints — extending interfaces
Viewed 0 times
generic constraintextendstype parameterRecordkeyoftype narrowing
Error Messages
Problem
Generic function needs to access properties on the type parameter but TypeScript says 'Property X does not exist on type T'. The generic is too broad and TypeScript cannot infer available properties.
Solution
Use generic constraints with extends: function getLength<T extends { length: number }>(item: T): number { return item.length; }. Common patterns: (1) T extends Record<string, unknown> for object types. (2) T extends readonly unknown[] for arrays. (3) T extends (...args: any[]) => any for functions. (4) T extends keyof SomeType for valid property names. (5) Multiple constraints: T extends A & B. (6) Default type: <T = string>. The constraint tells TypeScript what properties are guaranteed to exist.
Why
Without constraints, T could be anything including number or null, which don't have the property you're accessing. Constraints narrow the set of types T can be.
Revisions (0)
No revisions yet.