Grokking TypeScript
Vote

0% completed

​

Generic Constraints

Reading a property on a type parameter looks harmless, but the compiler rejects it:

function getLength<T>(item: T): number { return item.length; // Error }
error TS2339: Property 'length' does not exist on type 'T'.

The compiler checks the body of a generic function once, when it reads the declaration, and not once for each call. At that point T could be any type at all, including number and boolean, which have no length. The body may therefore use only what is valid for every possible type, and that is very little.

Adding a Constraint

To use

.....

.....

.....

Like the course? Get enrolled and start learning!

Reading Progress

0%


Vote for new content