繁体   English   中英

TypeScript自动转换型转integer

[英]TypeScript automatic conversion type to integer

I'm changing my application from ActionScript to Javascript/TypeScript (because of Flash Player) and I came across a problem, the types of ActionScript automatically converts the number to the given type and I was wondering if this is possible with TypeScript.

例子:

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

test(1.5, 3.7)

我知道我可以为此使用Math.trunc function,但想象一下,如果我有几个 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来保持 integer 值。

那么这可以通过 Javascript/TypeScript 实现吗? 如果没有,是否有其他语言的建议让我迁移?

Typescript 或 Javascript 中没有int类型。

如果您厌倦了键入Math.trunc ,为什么不像这样声明一个 function 变量:

let int = Math.trunc;  // Or choose a name you like
console.log(int(48.9)); // Outputs 48

不,这不能自动完成。 Typescript 甚至没有int类型(BigInt 除外,这是另一回事)

您可以使用更高阶的实用程序 function 自动转换数字 arguments 并用它包装您的函数:

 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)

这样,它会自动将任何数字 arguments 转换为整数,而无需您在任何地方都这样做

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM