BeginnerCoder

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.

Want it another way?
Task

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.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with TypeScript Foundations

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.