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.
Example:
function test(x: int, y: int){
console.log(x, y) //output: 1, 3
}
test(1.5, 3.7)
I know I can use the Math.trunc
function for this, but imagine if I have several int parameters and variables:
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)
}
Note: I'm having to use Math.trunc
all the time to keep the integer value.
So this is possible with Javascript/TypeScript? If not, there are remendations from other languages for me to migrate?
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.
Example:
function test(x: int, y: int){
console.log(x, y) //output: 1, 3
}
test(1.5, 3.7)
I know I can use the Math.trunc
function for this, but imagine if I have several int parameters and variables:
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)
}
Note: I'm having to use Math.trunc
all the time to keep the integer value.
So this is possible with Javascript/TypeScript? If not, there are remendations from other languages for me to migrate?
Share Improve this question asked Mar 17, 2021 at 3:01 SlinidySlinidy 3871 gold badge4 silver badges15 bronze badges2 Answers
Reset to default 3There is no int
type in Typescript or Javascript.
Why not just declare a function variable like this, if you are tired of typing Math.trunc
:
let int = Math.trunc; // Or choose a name you like
console.log(int(48.9)); // Outputs 48
No this can't be done automatically. Typescript doesn't even have an int
type (except for BigInt, which is a whole other thing)
You could make a utility higher order function that auto-converts number arguments and wrap your functions with it though:
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)
That way it will automatically convert any number arguments to ints with out you having to do it everywhere