Lesson 16 — Generic constraints
Limit what T can be
A plain T can be anything, so TypeScript will not let you read t.length — a number has no length. A constraint with extends says "T can be any type, as long as it has these properties": <T extends { length: number }>. Strings and arrays pass; numbers do not.
function hasItems<T extends { length: number }>(x: T) {
return x.length > 0;
}
hasItems("hi"); hasItems([1]); // ok
// hasItems(5); ← error
Why it matters: constraints let generic code use properties safely while staying flexible.
Constrain T to have a length, and return whichever argument is longer. Expect hello, then [ 1, 2, 3 ].
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based TypeScript Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for TypeScript Foundations books — check the publication year so the examples match current versions.
Search Amazon →