Home > OS >  After shifting an array This condition will always evaluate to false
After shifting an array This condition will always evaluate to false

Time:10-20

I'm writing some code for work, and am having an issue with typescript not realizing that I've changed the array.

function example() {
  const arr = [1,2,3,4,5,6,7];
  switch (arr[0]) {
    case 1:
      arr.shift();
      if (arr[0] === 2) {// Typescript complains that this will always evaluate to false
        console.log(2);
      }
      break;
  }
}

I know that I can get around this by casting arr[0] as a number, but is there any other way to inform typescript that I've modified the array?

Sorry if this is a duplicate, I've googled a bit before posting here and couldn't find any relevant discussion.

CodePudding user response:

Seams like you found a bug !

The assumption the compiler make is true without the the shift because arr[0] is narrowed to 1 thanks to the switch case.

But since shift() changes the array in place, the compiler is making a wrong assumption here.

function example() {
  const arr = [1,2,3,4,5,6,7];
  switch (arr[0]) {
    case 1:
      arr.shift();
      const two = arr[0]; // 
        //  ^? '1'
      console.log(two); // 2
      break;
  }
}

Playground


Yup, it's a known bug (pointed by this one closed as duplicate)

  • Related