I have a property that can receive a number between 0 and 256. How to type such a range in typescript?
function foo(threshold:number){
//do stuff
}
I have a property that can receive a number between 0 and 256. How to type such a range in typescript?
function foo(threshold:number){
//do stuff
}
A simpler version of @Pluto's function:
function foo(threshold: number): boolean {
return 0 <= threshold && threshold <= 256;
}
Inspired by this blog post: https://basarat.gitbook.io/typescript/main-1/nominaltyping .
enum SmallIntBrand { _ = "" }
type SmallInt = SmallIntBrand & number;
function isSmallInt(n: number): n is SmallInt {
return Number.isInteger(n) &&
0 <= n &&
n <= 255;
}
const a = 434424;
const b = 25;
function requiresSmallInt(n: SmallInt) {
console.log("Received number: " + n);
}
// Neither of these compile, for none of them
// have checked the variable with 'isSmallInt'.
//requiresSmallInt(a);
//requiresSmallInt(b);
if (isSmallInt(a)) {
requiresSmallInt(a);
}
if (isSmallInt(b)) {
requiresSmallInt(b);
}
You need to use the || operator ,If one of the conditions is incorrect ,then the condition will not enter the if :
function foo(threshold: number):boolean {
if (threshold < 0 || threshold > 256) {
return false;
}
return true;
}
Look at this code :
console.log(foo(-1)); // false
console.log(foo(5)); // true
console.log(foo(280)); // false
Also you can use with && operator , only if both conditions are true, then the condition will enter the if :
function foo(threshold: number):boolean {
if (threshold > 0 && threshold < 256) {
return true;
}
return false;
}
console.log(foo(-1)); // false
console.log(foo(5)); // true
console.log(foo(280)); // false
You wouldn't type it really. You would handle that separately:
function foo(threshold: number) {
if (threshold < 0 || threshold > 256) {
return;
}
// Whatever you want to do if threshold is OK
}