Open In App

TypeScript Working with Constrained Values

Last Updated : 11 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

z179

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);


Output:
z174

Explanation:

Lets say we have an interface of sports and it contains a property called name of type string. We created a variable sport of type Sports and assigned the name “baseball”. We have a function called printSportName which expects an argument of type T. Now, to ensure that this Type T is of type Sports, we use the keyword ‘extends’ with Sports. This checks, if the arguments passed through the function, are of type Sports before the function execution.

Conclusion:

In this article, we learnt that there is a problem while using Generic Contrains that the function promises to return the same kind of object as was passed in, not just some object matching the constraint.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads