October 2017
Intermediate to advanced
280 pages
6h 50m
English
Another typical use of generics is for defining functions that operate over a set of types. For example, we may define an identity function that accepts an argument of type T and returns it:
function identity<T>(arg: T) {
return arg;
}
However, in some cases, we may want to use only the instances of the types that have some specific properties. For achieving this, we can use an extended syntax that allows us to declare that we want the types used as type parameters to be subtypes of the given type:
interface Comparable {
compare(a: Comparable): number;
}
function sort<T extends Comparable>(arr: Comparable[]): Comparable[] {
// ...
}
For example, here, we defined an interface called Comparable. It has a single operation ...
Read now
Unlock full access