![]() |
TypeScript constraints are used in generic type declarations to restrict the types that can be used as type arguments for the generic. Constraints allow you to specify that a generic type parameter must meet certain criteria, such as implementing a particular interface, having a specific method, or extending a specific class. This ensures type safety and enhances code predictability. Syntax:function functionName<T extends ConstraintType>(param: T): ReturnType { Parameters:
Example 1: In this example, we are getting some parameters and we are restricting that parameter, which means the parameter value can be anything other than a number. and it returns the output according to their length method. Javascript
Output: "x is smaller than y" Example 2: In this example, we are giving numbers as a parameter and it is throwing error as numbers do not have length method. this is how we can limit the type. Javascript
Output: "x is smaller than y" |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |