Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript doesn't understand that array shift mutates the values of array from initialization #48204

Closed
workinggrafton opened this issue Mar 10, 2022 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@workinggrafton
Copy link

workinggrafton commented Mar 10, 2022

Bug Report

TypeScript doesn't understand that array shift mutates the values of the array.

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAHjAvDA2gRgDQwExYMwC6A3AFAkCWAZjABRwoAMBSiyaAlDAN4kzwB0EABZUoNdqT5Va9Ji2TZOPPn1CQQAGwCm-DSADmNAOQgA1kYm8YAXxLWgA

🔎 Search Terms

Array
shift
unshift

🕗 Version & Regression Information

Happens on nightly, currently failing on 4.7.0 also.

Playground Link

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAHjAvDA2gRgDQwExYMwC6A3AFAkCWAZjABRwoAMBSiyaAlDAN4kzwB0EABZUoNdqT5Va9Ji2TZOPPn1CQQAGwCm-DSADmNAOQgA1kYm8YAXxLWgA

💻 Code

const x: number[] = [1, 2, 3];
if (x[0] === 1) {
  x.shift();
  if (x[0] === 2) {    // <--- Error here.
    console.log('ok');
  }
}

🙁 Actual behavior

Error evaluating x[0] after a shift. TypeScript thinks array values are fixed to the values from initialization.

🙂 Expected behavior

Error evaluating x[0] is typed as 'number', not a numeric literal (i.e. no error in example, console statement is reachable and prints).

@fatcerberus
Copy link

fatcerberus commented Mar 10, 2022

#9998.

TypeScript thinks array values are fixed to the values from initialization.

It doesn't actually think this - it optimistically assumes the .shift() call has no side effects and therefore that the previous narrowing check (x[0] === 1) hasn't been invalidated.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 10, 2022
@typescript-bot
Copy link
Collaborator

typescript-bot commented Mar 13, 2022

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants