Constraint Narrowing in Function Bodies
What you'll learn: How to safely access properties on generic type parameters inside function implementations by leveraging their constraints.
When you write a generic function with a constraint, TypeScript knows that your type parameter meets certain requirements. Inside the function body, you can access any properties or methods guaranteed by that constraint — and TypeScript will enforce type safety.
The Core Idea
Think of a constraint like a security clearance: if you require that T extends { name: string }, TypeScript knows that whatever T ends up being, it will definitely have a name property. This means you can safely access value.name inside your function without TypeScript complaining.
function greet<T extends { name: string }>(person: T): string {
// Safe! TypeScript knows 'name' exists because of the constraint
return `Hello, ${person.name}`;
}
greet({ name: "Alice", age: 30 }); // "Hello, Alice"
Without the constraint, trying to access person.name would cause an error because TypeScript wouldn't know if name exists on type T.
Using Multiple Constraint Properties
If your constraint specifies multiple properties, you can access all of them:
function summarize<T extends { id: number; label: string }>(item: T): string {
return `Item #${item.id}: ${item.label}`;
}
Method Access Through Constraints
Constraints also let you call methods:
function logLength<T extends { length: number }>(value: T): void {
console.log(`Length: ${value.length}`);
}
logLength("hello"); // Works: string has length
logLength([1, 2, 3]); // Works: array has length
Key Takeaway: Constraints don't just restrict what types you can pass — they also unlock safe property and method access inside your generic function body, because TypeScript guarantees those members exist.