Search⌘ K

Extending Types in Generics

Explore how to use the extends keyword in TypeScript generics to limit types to specific subsets like strings, numbers, or booleans. Learn to constrain values for enhanced type safety and maintainability in reusable code components.

Extending generics types

Let’s say we wanted to limit the value of our linked list node to only support strings, numbers, and booleans. In TypeScript, constraints are expressed using the extends keyword. T extends K means it’s safe to presume that a value of type T is also of type K. An easy way of thinking about this is to just imagine we’re writing something with extends as a variable assignment.

Let’s take 19 ...