Constraining to Arrays and Iterables
You'll learn how to restrict generic type parameters to array or iterable types, ensuring your generic functions and classes only accept collections.
Why Constrain to Collections?
Sometimes you write a generic function that must work with arrays or other iterable collections. Without a constraint, TypeScript lets someone pass anything — including primitives or objects that don't support iteration. Constraining to Array or Iterable ensures your type parameter represents a collection you can actually loop over or manipulate.
Array-Specific Constraints
When you need array methods like push, pop, or length, constrain to the array type:
function getLastElement<T extends any[]>(arr: T): T[number] | undefined {
return arr[arr.length - 1];
}
const last = getLastElement([1, 2, 3]); // number | undefined
Here T extends any[] means "T must be some kind of array." The T[number] syntax extracts the element type.
Iterable Constraints
For broader compatibility (arrays, strings, sets, maps), constrain to Iterable<T>:
function firstValue<T>(iterable: Iterable<T>): T | undefined {
for (const value of iterable) {
return value;
}
return undefined;
}
firstValue([1, 2, 3]); // works
firstValue("hello"); // works (string is iterable)
firstValue(new Set([4, 5])); // works
This accepts anything you can use in a for...of loop.
Choosing the Right Constraint
Use any[] when you need array-specific methods. Use Iterable<T> when you only need iteration. This balance gives type safety while maximizing reusability.
Key Takeaway: Constraining generics to any[] or Iterable<T> ensures type safety when working with collections, preventing misuse while supporting arrays, strings, and other iterable types.