VOOZH about

URL: https://www.geeksforgeeks.org/typescript/typescript-generic-constraints/

⇱ TypeScript Generic Constraints - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

TypeScript Generic Constraints

Last Updated : 4 Sep, 2024

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.

What are Generic Constraints?

  • TypeScript Generics allows us to write reusable code by working with different data types. We can create functions, classes, or interfaces that can work with different data types.
  • Generics are defined as <T> and This type of T is used to define the type of function arguments, return values, etc.
  • Generic Constraints are used to specify limits to the types that can be used with generic type parameters.
  • This results in type checking and these conditions ensure that variables have a certain type of value before they are used in the context.
  • This check minimizes the occurrence of runtime errors.

Syntax:

function genericConstraintFunction<T extends GenericConstraintType>(param: T): void {
 // ...
}

Where-

  • T is the generic type parameter.
  • `extends` GenericConstraintType specifies the constraint that Type T should be extending GenericConstraintType type.

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:

baseball

Example 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 : 9

Example 3: In this example, we ensure that the generic type parameter class object implements a specific interface.

Output:

Number of Gloves required are : 18
Comment
Article Tags:

Explore