![]() |
VOOZH | about |
In TypeScript, generic constraints restrict the types that can be used with a generic type by using the extends keyword. This ensures that the generic type adheres to a specific structure or interface, allowing access to certain properties or methods within the generic type.
function genericConstraintFunction<T extends GenericConstraintType>(param: T): void {
// ...
}Where-
Example 1: In this example, the Sports interface has a name property. The printSportName function uses extends to ensure its argument conforms to the Sports type before execution.
Output:
baseballExample 2: In this example, we use extends keyof to ensure that the generic type parameter K is a key of type T. This enforces that K is a valid property of T.
Output:
Number of Players are : 9Example 3: In this example, we ensure that the generic type parameter class object implements a specific interface.
Output:
Number of Gloves required are : 18