首页 > 解决方案 > 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");

这是错误的图片,谢谢

标签: javascripttypescript

解决方案


这不是 switch 语句的工作方式。

如果你要写:

switch (true) {
    case todoList:
      if (todoList.length >= 5) { //todoList is null???
        console.log("LIST IS FULL!");
      }
      break;
  }

它会起作用,因为在 switch 语句中,您正在检查情况是否为真。

Switch 语句采用原始值,例如布尔值、字符串、数字等。

您尝试使用 switch 语句的方式更复杂,并且只能与 if 语句一起使用。


推荐阅读