Как указать диапазон min-max для числа в Typescript? - PullRequest
0 голосов
/ 28 мая 2020

У меня есть свойство, которое может принимать числа от 0 до 256. Как ввести такой диапазон в машинописный текст?

function foo(threshold:number){
//do stuff
}

Ответы [ 3 ]

1 голос
/ 28 мая 2020

Вам необходимо использовать оператор ||. Если одно из условий неверно, то условие не будет входить в if:

    function foo(threshold: number):boolean {
      if (threshold < 0 || threshold > 256) {
        return false;
      }
        return true;
    }

Посмотрите на этот код:

console.log(foo(-1)); // false
console.log(foo(5)); // true
console.log(foo(280)); // false

Также вы можете использовать с оператором &&, только если оба условия верны, тогда условие будет вводить 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
1 голос
/ 28 мая 2020

Если вы просто хотите проверить его во время выполнения:

Более простая версия функции @ Pluto:

function foo(threshold: number): boolean {
    return 0 <= threshold && threshold <= 256;
}

Если вы хотите, чтобы это было проверено типом:

На основе этого сообщения в блоге: https://basarat.gitbook.io/typescript/main-1/nominaltyping.

Ссылка на Typescript Playground

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);
}
1 голос
/ 28 мая 2020

Ты бы не стал его печатать. Вы бы обработали это отдельно:

function foo(threshold: number) {
  if (threshold < 0 || threshold > 256) {
    return;
  }
  // Whatever you want to do if threshold is OK
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...