Generic Constraint: Has Length
Write a generic function that accepts any type that has a length property (string, array, etc.). Use a generic constraint: <T extends { length: number }>. Return the length and the last element (as a string).
TypeScript's generic constraints allow you to specify that a type parameter must have certain properties. The constraint T extends { length: number } ensures that only types with a numeric length property can be passed.
This demonstrates how generics can be constrained to specific shapes while remaining flexible across different concrete types.
Generic constraints with the extends keyword allow you to restrict type parameters to types that have certain properties. The constraint <T extends { length: number }> ensures the function works with strings, arrays, and any other types that have a length property.
This pattern is widely used in TypeScript libraries to define type-safe APIs that work across multiple data types while enforcing structural requirements.
Generic constraints ensure type safety while allowing flexibility across different concrete types. The constraint T extends { length: number } guarantees that any passed type has a numeric length property, enabling the function to work with both strings and arrays.
This pattern appears in TypeScript's standard library with functions like Array.prototype.map and is fundamental to building type-safe abstractions.
Example Input & Output
Algorithm Flow

Solution Approach
Best Answers
function describeLength(item: any): any {
if (item.length === 0) return {length: 0, last: ""};
if (typeof item === "string") return {length: item.length, last: item.charAt(item.length - 1)};
return {length: item.length, last: item[item.length - 1]};
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
