CodePark/ questions / Generics
START PRACTICINGPRACTICE
Frontend question · TypeScript › Generics

Which call is a compile error?

function len<T extends { length: number }>(x: T) {
  return x.length;
}
len(42)

The answer is len(42). The constraint requires a length: number property, and a number does not have one.

The other calls are fine. Strings, arrays and the object literal
{ length: 3 } all have a length property. Note that without the constraint, x.length itself would not compile inside the function.