Skip to content

Array indices are possibly 'undefined' #18718

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

Closed
aminpaks opened this issue Sep 23, 2017 · 3 comments
Closed

Array indices are possibly 'undefined' #18718

aminpaks opened this issue Sep 23, 2017 · 3 comments
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@aminpaks
Copy link
Contributor

aminpaks commented Sep 23, 2017

TypeScript Version: 2.5.2

Code

function test(statement: string): string {
  const parts = statement.split('-'); // <- parts will have at least one element
  let firstElement = parts.shift(); // <- firstElement cannot be undefined at this point

  if (parts.length > 1) {
    let secondElement = parts.shift(); // <- Still says that secondElement may be undefined!
  }
}
test('first-second');

Expected behavior:

  • String prototype split method always creates an array with at least one elements and therefore shift method cannot produce an undefined type.
  • Once we check the length of an array shift, pop cannot produce undefined type.

Actual behavior:
shift, pop methods or accessing arrays indices return undefined even though the array has elements.

@DanielRosenwasser DanielRosenwasser added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Sep 23, 2017
@DanielRosenwasser
Copy link
Member

DanielRosenwasser commented Sep 23, 2017

There's not an easy way to communicate the probing you're doing with the return type of the methods using the type system today. You can convince the type system you know what you're doing with the non-null assertion operator (i.e. the ! operator):

let secondElement = parts.shift()!;

@kitsonk
Copy link
Contributor

kitsonk commented Sep 24, 2017

Duplicate of #11117

@mhegazy
Copy link
Contributor

mhegazy commented Oct 9, 2017

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

@mhegazy mhegazy closed this as completed Oct 9, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

4 participants