How do you constrain a generic type parameter using 'extends' to require it has certain properties?
Short answer
Write ` ` to restrict T to only types that are assignable to SomeShape, letting you safely access SomeShape's properties inside the function while still preserving T's more specific inferred type for the return value.
Advertisement
AModel answer
Write `<T extends SomeShape>` to restrict T to only types that are assignable to SomeShape, letting you safely access SomeShape's properties inside the function while still preserving T's more specific inferred type for the return value.
function getLength<T extends { length: number }>(item: T): number {
return item.length;
}
getLength('hello'); // OK -- strings have .length
getLength([1, 2, 3]); // OK -- arrays have .length
// getLength(42); // Error: number doesn't have .lengthReal-world example
Writing a reusable utility that needs to access a common property (like .length or .id) across otherwise different input types.
Likely follow-ups
- How would you constrain T to require a specific method rather than just a property?
Related topics