Constraints and Generic Types

A constraint says the type parameter must have something. <T extends { length: number }> means 'anything with a length'.

Without it you cannot use .length inside the function, because T might be a number. extends here means 'at least this shape', not inheritance.

Try it

Remove the constraint and watch a.length become an error instead. The constraint is what buys you the ability to use the property.

loading editor…

checking…

Strings and arrays both have length, so both work and both keep their type. Numbers do not, and the error says so directly.

Types take parameters too. Array<string>, Promise<Book>, Record<string, number>, Map<string, Book>.

Writing your own is worth it once the same wrapper shape holds several kinds of payload, which is exactly what an API response looks like: type ApiResponse<T> = { results: T[]; count: number }.

◈ Graded Types

Write a generic function called pluck that takes an array of objects and a key, and returns an array of the values at that key, with the right type. pluck([{a: 1}, {a: 2}], "a") must produce a number[], and asking for a key that does not exist must be rejected. Use a constrained type parameter rather than any.

Checked against the compiler, not against how you wrote it. 2 visible and 3 hidden checks.

loading editor…
real tsc, strict mode

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back