HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptModeratepending

TypeScript generic constraints — extending interfaces

Submitted by: @anonymous··
0
Viewed 0 times
generic constraintextendstype parameterRecordkeyoftype narrowing

Error Messages

Property does not exist on type T
Type T is not assignable to type

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.