TypeScript Working with Constrained Values
Last Updated :
24 Apr, 2025
TypeScript Working with Constrained Values specifies how can we deal with Constrained Values. 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. But there is a common error when working with generic constraints; The problem is that the function promises to return the same kind of object as was passed in, not just some object matching the constraint.
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, we are getting error while using constrained value.
JavaScript
function gfg<Type extends { index: number }>(
obj: Type,
x: number
): Type {
if (obj.index >= x) {
return obj;
} else {
return { index: x };
}
}
Output:

Explanation
It might look like this function is OK - Type is constrained to { index: number }, and the function either returns Type or a value matching that constraint. The problem is that the function promises to return the same kind of object as was passed in, not just some object matching the constraint. If this code were legal, you could write code that definitely wouldn’t work:
Example 2: In this example, we will see how can we correctly use contraint values in Typescript.
JavaScript
interface Sports {
name: string;
}
function printSportName<T extends Sports>(sport: T): void {
console.log(sport.name);
}
let sport: Sports = { name: "baseball" };
printSportName(sport);