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.
Read more
- Generics (https://www.typescriptlang.org/docs/handbook/2/generics.html)typescriptlang.org