TypeScript自动将类型转换为整数



我正在将我的应用程序从ActionScript更改为Javascript/TypeScript(因为Flash Player(,我遇到了一个问题,ActionScript的类型会自动将数字转换为给定的类型,我想知道TypeScript是否可以做到这一点。

示例:

function test(x: int, y: int){
console.log(x, y) //output: 1, 3
}
test(1.5, 3.7)

我知道我可以使用Math.trunc函数,但想象一下,如果我有几个int参数和变量:

function test(x: number, y: number, w: number, h: number){
x = Math.trunc(x)
y = Math.trunc(y)
w = Math.trunc(w)
h = Math.trunc(h)

other: number = 10;
x = Math.trunc(x / other)
}

注意:我不得不一直使用Math.trunc来保持整数值。

那么这在Javascript/TypeScript中是可能的吗?如果没有,还有其他语言的建议​​让我迁移?

Typescript或Javascript中没有int类型。

如果您厌倦了键入Math.trunc:,为什么不直接声明这样的函数变量呢

let int = Math.trunc;  // Or choose a name you like
console.log(int(48.9)); // Outputs 48
不,这不能自动完成。Typescript甚至没有int类型(除了BigInt,它是另一回事(

你可以制作一个实用程序的高阶函数,它可以自动转换数字参数,并用它包装你的函数:

function argsToInt(func) {
return function(...args) {
const newArgs = args.map(
arg => typeof arg === 'number' ? Math.trunc(arg) : arg
);
return func(...newArgs);
}
}
function add(a, b) { 
return a + b 
}
const addInts = argsToInt(add);
console.log(addInts(2.532432, 3.1273))
console.log(addInts(2.532432, 3.1273)  === 5)

这样,它将自动将任何数字参数转换为int,而无需在任何地方进行