Hur specificerar man ett min-max intervall för ett tal i Typescript?
Jag har en egenskap som kan ta emot ett nummer mellan 0 och 256. Hur skriver man ett sådant intervall i TypeScript?
function foo(threshold:number){
//do stuff
}Svar #1
Du behöver använda || -operatorn. Om ett av villkoren är felaktigt, kommer villkoret inte att gå in i if :
function foo(threshold: number):boolean {
if (threshold < 0 || threshold > 256) {
return false;
}
return true;
}
Titta på den här koden:
console.log(foo(-1)); // false
console.log(foo(5)); // true
console.log(foo(280)); // false
Du kan också använda &&-operatorn, endast om båda villkoren är sanna, då kommer villkoret att gå in i 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
Svar #2
Om du bara vill kontrollera det vid körning:
En enklare version av @Plutos funktion:
function foo(threshold: number): boolean {
return 0 <= threshold && threshold <= 256;
}
Om du vill att det ska typkontrolleras:
Inspirerad av detta blogginlägg: https://basarat.gitbook.io/typescript/main-1/nominaltyping .
Typescript Playground-länk
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);
}
