How to Restrict a Number to a Certain Range in TypeScript ?
Last Updated :
24 Apr, 2025
Restricting a number to a certain range in TypeScript means ensuring that a numerical value falls within specific bounds or limits. This process, often referred to as "clamping" or "bounding," prevents a number from going below a minimum value or exceeding a maximum value.
For example, if you have a requirement that a variable representing a person's age should always be between 0 and 100, restricting the number to this range ensures that the age remains a valid value.
Below are the approaches used to restrict a number to a certain range:
Approach 1: Using Math.min
and Math.max
In this we use Math.min
to ensure the value isn't below the minimum and Math.max
to cap it at the maximum.
Example: In this example, we are using Math.min
and Math.max.
JavaScript
function numbers(value: number, min: number, max: number):
{ result: number, message: string } {
const num = Math.min(Math.max(value, min), max);
let message: string;
if (num === value) {
message = `Number ${value} is within
the range of ${min} to ${max}.`;
} else if (num === min) {
message = `Number ${value} is below
the lower limit of ${min}.`;
} else {
message = `Number ${value} exceeds
the upper limit of ${max}.`;
}
return { result: num, message };
}
let value: number = 15;
let min: number = 5;
let max: number = 10;
let resultObject = numbers(value, min, max);
console.log(resultObject.result);
console.log(resultObject.message);