TypeScript Constraints
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 {
// Function implementation
}
Parameters:
- T is the generic type parameter.
- extends is used to specify the constraint.
- ConstraintType is the type or interface that T must extend or implement.
- param is the parameter that must be of type T.
- ReturnType is the return type of the function.
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
function whatIsLength<Type extends { length: number }> (x: Type, y: Type) { if (x.length >= y.length) { return ( "x is larger than y" ); } else { return ( "x is smaller than y" );; } } const ans = whatIsLength([4, 0], [8, 9, 0]); console.log(ans); const ans1 = whatIsLength( "abcde" , "bb" ); console.log(ans1); |
Output:
"x is smaller than y"
"x is larger 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
function whatIsLength<Type extends { length: number }> (x: Type, y: Type) { if (x.length >= y.length) { return ( "x is larger than y" ); } else { return ( "x is smaller than y" );; } } const ans = whatIsLength([4, 0], [8, 9, 0]); console.log(ans); const ans1 = whatIsLength( "abcde" , "bb" ); console.log(ans1); // Errror as values are number // and they do not have length method const ans2 = whatIsLength(10, 12); console.log(ans2); |
Output:
"x is smaller than y"
"x is larger than y"
Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.
Contact Us