如何在 Typescript 中指定数字的最小-最大范围?

Don*_*al0 8 typescript

我有一个属性可以接收 0 到 256 之间的数字。如何在打字稿中输入这样的范围?

function foo(threshold:number){
//do stuff
}
Run Code Online (Sandbox Code Playgroud)

Plu*_*uto 6

您需要使用||运算符,如果其中一个条件不正确,则该条件将不会输入if

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

看看这段代码:

console.log(foo(-1)); // false
console.log(foo(5)); // true
console.log(foo(280)); // false
Run Code Online (Sandbox Code Playgroud)

也可以使用 with&&运算符,只有当两个条件都为 true 时,条件才会输入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
Run Code Online (Sandbox Code Playgroud)


Mel*_*nWM 5

如果您只想在运行时检查它:

@Pluto 函数的更简单版本:

function foo(threshold: number): boolean {
    return 0 <= threshold && threshold <= 256;
}
Run Code Online (Sandbox Code Playgroud)

如果您希望对其进行类型检查:

受到这篇博文的启发: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);
}
Run Code Online (Sandbox Code Playgroud)

  • 品牌类型(以及更普遍的不透明类型)是一种可行的选择,但当您有范围时通常很难使用。无论哪种情况,您仍然需要执行“if (isValid(x))”,因此您最终不会获得那么多编译器支持。如果你没有支票,它确实会对你大喊大叫,这就是你得到的。 (2认同)