gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:38:20 29 4
gpt4 key购买 nike

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

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

最佳答案

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

@Pluto 函数的更简单版本:

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

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

灵感来自这篇博文: https://basarat.gitbook.io/typescript/main-1/nominaltyping .

Typescript Playground link

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);
}

关于typescript - 如何在Typescript中指定数字的最小-最大范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62061507/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com