我有一个属性可以接收 0 到 256 之间的数字。如何在打字稿中输入这样的范围?
function foo(threshold:number){
//do stuff
}Run Code Online (Sandbox Code Playgroud)
您需要使用||运算符,如果其中一个条件不正确,则该条件将不会输入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)
@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。
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)
| 归档时间: |
|
| 查看次数: |
15910 次 |
| 最近记录: |