Generics
Generics allow you to create reusable components and functions that can work with multiple types. With generics, you can parameterize types, functions, and interfaces, allowing them to operate on different types without explicitly specifying them beforehand.
Generics allow you to make code more flexible and reusable.
Generic Type
To define a generic type, you use angle brackets (<>
) to specify the type parameters, for instance:
Generic Classes
Generics can be applied also to classes, in this way they can work with multiple types by using type parameters. This is useful to create reusable class definitions that can operate on different data types while maintaining type safety.
Generic Constraints
Generic parameters can be constrained using the extends
keyword followed by a type or interface that the type parameter must satisfy.
In the following example T it is must containing a properly length
in order to be valid:
An interesting feature of generic introduced in version 3.4 RC is Higher order function type inference which introduced propagated generic type arguments:
This functionality allows more easily typed safe pointfree style programming which is common in functional programming.
Generic contextual narrowing
Contextual narrowing for generics is the mechanism in TypeScript that allows the compiler to narrow down the type of a generic parameter based on the context in which it is used, it is useful when working with generic types in conditional statements: