Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error TS7027: Unreachable code detected typescript

  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.

like image 480
Nancy Avatar asked Aug 18 '26 11:08

Nancy


1 Answers

You have if condition on second line of function as:

if(true)

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 you want the code inside if to always execute, you can bring it out of if/else condition.

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
like image 66
ashfaq.p Avatar answered Aug 20 '26 02:08

ashfaq.p