错误TS7027:检测不到打字稿代码 [英] error TS7027: Unreachable code detected typescript

查看:60
本文介绍了错误TS7027:检测不到打字稿代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  sortArrayDate(arrayToSort, arrayDateKey, ascendingOrDecending) {
    if (true) {
      arrayToSort.sort(function(a, b){
        if (a[arrayDateKey] === '' || a[arrayDateKey] === null) {
          return 1;
        }
        if (b[arrayDateKey] === '' || b[arrayDateKey] === null) {
          return -1;
        }
        return new Date(a[arrayDateKey]).getTime() - new Date(b[arrayDateKey]).getTime();
   });
    } else {
        arrayToSort.sort(function(a, b){  //getting error
        if (a[arrayDateKey] === '' || a[arrayDateKey] === null) {
          return 1;
        }
        if (b[arrayDateKey] === '' || b[arrayDateKey] === null) {
           return -1;
        }
        return new Date(b[arrayDateKey]).getTime() - new Date(a[arrayDateKey]).getTime();
      });
    }
  }

我在上述代码行中遇到上述错误.代码有什么问题.我正在尝试从数组中排序日期.

I am getting the above error on the mentioned line.Whats the issue with the code. I am trying to sort dates from an array.

推荐答案

函数第二行的if条件为:

You have if condition on second line of function as:

if(true)

然后还有其他部分.首先,如果if始终为真,则永远不会达到/调用.这就是为什么打字稿会出现无法访问的代码错误.

And then you have else part as well. Since first if will always be true, else can never be reached/called. That is why typescript is giving the unreachable code error.

如果希望始终执行内部代码,则可以使其脱离 if/else 条件.

If you want the code inside if to always execute, you can bring it out of if/else condition.

为了在不更改代码的情况下禁用此错误(不建议),可以使用 tsconfig.json 更改编译器配置.添加此内容可消除此警告:

In order to disable this error without changing the code (not recommended), you can change the compiler config using tsconfig.json. Add this to disbale this warning:

"allowUnreachableCode": true

这篇关于错误TS7027:检测不到打字稿代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆