Code Logo

Generic Constraint: Has Length

Published at24 Jul 2026
TypeScript Functions Medium 0 views
Like0

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

Example 1
Input
"hello"
Output
{"length":5,"last":"o"}
Example 2
Input
"abcde"
Output
{"length":5,"last":"e"}
Example 3
Input
"a"
Output
{"length":1,"last":"a"}
Example 4
Input
"ts"
Output
{"length":2,"last":"s"}
Example 5
Input
""
Output
{"length":0,"last":""}

Algorithm Flow

Recommendation Algorithm Flow for Generic Constraint: Has Length
Recommendation Algorithm Flow for Generic Constraint: Has Length

Solution Approach

Use the generic constraint T extends { length: number }. Access item.length for the count. For string, use charAt(length-1); for arrays, use simple indexing.

Best Answers

typescript - Approach 1
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]};
}