打字稿:类型“布尔”与类型“数字”不可比较

prg*_*grm 6 typescript

我肯定错过了什么。我有这个功能:

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

当我尝试编译它时,出现以下错误:

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:
              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

我希望能够比较数字。我在这里缺少什么?

Ter*_*rry 9

这是因为 forswitch/case 使用严格比较,即===,并且您正在将value数字与表达式进行比较,例如,value > 1 && value < 86400该表达式被评估为布尔值。

您应该改用 if/else 语句。请注意,您的 switch/case 代码没有默认返回,无论如何都会抛出错误:无论如何,您都需要捕获 value <= 1 且 value >= 259200 的原因:

transform(value: number): string {
    if (value > 1 && value < 86400) {
        return 'this';
    } else if (value > 86401 && value < 259200) {
        return 'that';
    } else {
        return 'something else';
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果他想继续使用“switch”,您也可以将“switch(value)”更改为“switch(true)”:https://repl.it/repls/WoefulHospitableMalware (6认同)

Cre*_*key 6

为清楚起见。开关/外壳中有两个不同的元件将被比较。第一个元素是您在括号中的“switch”关键字之后编写的内容(在您的情况下是一个数字)。第二个元素是您在“case”关键字之后编写的那些元素,它们是您的 case 中的条件语句。因此,这些语句在解析后的结果将始终是布尔值。这意味着您最终想要将数字与布尔值进行比较。嗯,由于 switch/case 使用了严格的比较,所以这个比较的结果总是 false。

switch (value) { // <-- First member of comparison (number)
    
      case value > 1 && value < 86400: /* <-- Second member of comparison 
      which will be a boolean after parsing it */
        return 'this';
        break;
      }
      
      /* Well you are trying to do that: 3 === true,
      but this is always false because of the strict comparison (===)       */
Run Code Online (Sandbox Code Playgroud)

一个可能的解决方法(不是非常漂亮的解决方案):

switch (true) { /* Use 'true' as the first member of the comparison 
and your code will be executed in those case 
when the condition evaluation is true in the 'case' block */
      case value > 1 && value < 86400:
        return 'this';
        break;
      }
Run Code Online (Sandbox Code Playgroud)