JS Built-ins
TypeScriptintermediate

Generics β€” getLength<T extends {length}>

πŸ“– Usage Example
function getLength<T extends { length: number }>(x: T): number { return x.length }
getLength([1, 2, 3])   // β†’ 3
getLength('hello')     // β†’ 5

A generic constraint T extends { length: number } allows the function to work on any 'lengthable'.

Generic Constraints

T extends { length: number } is a constraint β€” it allows any type that has a length property (arrays, strings, etc.).

Challenge: Implement getLength<T extends { length: number }>(x: T): number.

getLength([1, 2, 3])  // β†’ 3
getLength('hello')   // β†’ 5
πŸ’‘ Hints (1)
  • β€’ The constraint T extends { length: number } ensures .length is always available.