Explain generic constraints and provide a length-constrained generic example
Your grasp of bounding generics to shapes without losing type safety.
Explain that extends requires properties; show T extends { length: number }; give a generic function signature.
Using any or dropping extends.
WHAT THIS TESTS: This question checks whether you understand that generics without constraints are too permissive to access specific members safely. The interviewer wants to see that you know how to use the extends keyword to bound a type parameter to a structural shape, preserving both reusability and compile-time safety. It also reveals if you can distinguish between a generic constraint and a concrete interface or type alias.
A GOOD ANSWER COVERS: First, explain the purpose: generic constraints restrict the set of types that can be passed to a generic function so the compiler knows which properties are available. Second, provide the exact syntax for an object with a numeric length property, which is T extends { length: number }. Third, write a complete function signature such as function logLength<T extends { length: number }>(arg: T): T { console.log(arg.length); return arg; }. Fourth, note that the return type can still be T so the specific input type is preserved, unlike using any.
COMMON WRONG ANSWERS: Answering with function logLength(arg: any): any and saying it works because you can access dot length on anything. Proposing an interface Lengthable { length: number } and then writing function logLength(arg: Lengthable) without using a generic at all, which loses the identity of the original type. Forgetting the extends keyword and trying to access arg.length on an unconstrained T, which causes a TypeScript compiler error. Confusing generic type parameters with function parameters or runtime checks.
LIKELY FOLLOW-UPS: The interviewer might ask what happens if you pass a primitive like a string, which has a length property, and whether your constraint would accept it. They may ask how constraints differ from conditional types or how you would constrain T to have both a length and a name property. Another follow-up is why you would return T instead of { length: number }, which tests whether you understand preserving the specific type for downstream use.
ONE CONCRETE EXAMPLE: A strong concrete example is a generic logging utility that accepts arrays, strings, or custom objects as long as they have a length. You would write function logLength<T extends { length: number }>(arg: T): T { console.log(arg.length); return arg; } and then call it with an array like logLength([1, 2, 3]) or a string like logLength("hello"). In both cases TypeScript infers the specific type for T, so the returned value retains its exact type rather than being widened to any or a generic object shape.
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.