3

I want to use a boolean variable in a arithmetic operation in typescript, but the compiler complains: "The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type."

class User {
    hasFoo: boolean;
};
let user = new User();
let amount : number = BASE + FOO_FACTOR * user.hasFoo

I know that I can cast my boolean to the type <any> and it's working:

let amount : number = BASE + FOO_FACTOR * <any>user.hasFoo

But is it the best solution?

3
  • Why do you want to use a boolean variable in a arithmetic operation? TypeScript is about forcing types. At run-time, your boolean will be casted to a number anyways, so why don't you convert the boolean into a number explicitly? Commented Jun 20, 2018 at 9:48
  • 1
    Possible duplicate of In TypeScript, How to cast boolean to number, like 0 or 1 Commented Jun 20, 2018 at 9:49
  • Note you can also work around this issue by using the conditional operator, e.g. let amount: number = user.hasFoo ? BASE + FOO_FACTOR : BASE; or let amount: number = BASE + (user.hasFoo ? FOO_FACTOR : 0); Commented Jun 20, 2018 at 9:53

1 Answer 1

6

TypeScript wants you to enforce types at compile time. Your code works on runtime due to the internal weak typing of vanilla JavaScript.

Avoid any casting, instead convert the boolean to an actual number.

There are multiple options, e.g.:

let number: number = user.hasFoo ? 1 : 0

or:

let number: number = Number(user.hasFoo)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I'll use Number() in my function.

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.