Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Type "boolean" is not comparable to type "number"

Tags:

typescript

I must be missing something. I have this function:

  transform(value: number): string {
    switch (value) {
      case value > 1 && value < 86400:
        return 'this';
        break;
      case value > 86401 && value <  259200:
        return 'that';
        break;
    }
  }

When I try to compile it, I get these errors:

ERROR in src/app/time-transform.pipe.ts:10:12 - error TS2678: Type 'boolean' is not comparable to type 'number'.

10       case value > 1 && value < 86400:
              ~~~~~~~~~~~~~~~~~~~~~~~~~~
src/app/time-transform.pipe.ts:13:12 - error TS2678: Type 'boolean' is not comparable to type 'number'.

13       case value > 86401 && value <  259200:
              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I want to be able to compare numbers. What am I missing here?

like image 207
prgrm Avatar asked Jun 09 '26 22:06

prgrm


1 Answers

That is because for switch/case uses strict comparison, i.e. ===, and you are comparing value, which is a number, against an expression, e.g. value > 1 && value < 86400 that is evaluated as boolean.

You should be using if/else statements instead. Note that your switch/case code does not have a default return, which will throw an error anyway: you will need to catch causes where value <= 1 and value >= 259200 anyway:

transform(value: number): string {
    if (value > 1 && value < 86400) {
        return 'this';
    } else if (value > 86401 && value < 259200) {
        return 'that';
    } else {
        return 'something else';
    }
}
like image 163
Terry Avatar answered Jun 12 '26 13:06

Terry