April 2018
Beginner
536 pages
13h 21m
English
Sometimes, we don't need the concrete type required by a function, class, or method, but we know that such type must adhere to a certain set of rules.
For example, the following code snippet declares a generic function named isEquals. However, this time the type T has a constraint (T extends Comparable):
interface Comparable<T> { equals(value: T): boolean;}function isEqual<TVal, T extends Comparable<TVal>>(comparable: T, value: TVal) { return comparable.equals(value);}
The constraint is used to ensure that all the types provided to isEqual as its generic type argument implement the Comparable interface:
interface RectangleInterface { width: number; height: number;}type ComparableRectangle = RectangleInterface & Comparable<RectangleInterface>; ...