3

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 recommendations from other languages ​​for me to migrate?

2 Answers 2

3

There 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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.