TypeScript 中损坏的 switch 语句

我在 TypeScript 中遇到 switch 语句的问题


在多个代码编辑器上尝试过,我正在尝试使用 switch (true) 但由于某种原因代码在 switch 语句中失败。


const todoList: string[] | null = [];


function pushItemToTodoList(item: string) {

  //COMPILES!!

  if (todoList !== undefined && todoList !== null && todoList.length) {

    if (todoList.length >= 5) {

      console.log("LIST IS FULL!");

    }

  }


  //DOESN'T COPMILE!!

  switch (true) {

    case todoList !== undefined && todoList !== null && todoList.length:

      if (todoList.length >= 5) { //todoList is null???

        console.log("LIST IS FULL!");

      }

      break;

  }

}


pushItemToTodoList("clean house");


白猪掌柜的
浏览 362回答 2
2回答

Helenr

switch 语句本身不会失败。它很简单,不能容忍带有变量的 case 语句。也不是条件运算符,只有静态值。在编译时,switch 语句会构建 case 语句中所有静态值及其跳转位置的索引。不能在 case 语句中使用变量,因为在编译时,这些变量不应该被计算甚至不存在。Switch - Case 语句的性能非常好,因为带有静态值和跳转位置的索引是预编译的。不过,有一种方法可以解决这个特定问题,即在 switch 语句中将布尔逻辑与代数相结合,在 case 语句中将静态值结合起来。

小怪兽爱吃肉

这不是 switch 语句的工作方式。如果你会写:switch (true) {    case todoList:      if (todoList.length >= 5) { //todoList is null???        console.log("LIST IS FULL!");      }      break;  }它会起作用,因为在 switch 语句中您正在检查情况是否为真。Switch 语句采用原始值,例如布尔值、字符串、数字等。您尝试使用 switch 语句的方式更复杂,并且只能使用 if 语句。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript