Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

After shifting an array This condition will always evaluate to false

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading