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

Why isn't "a.length > 0" an type-guard that help me Narrowing? #46638

Closed
aiden271828 opened this issue Nov 2, 2021 · 1 comment
Closed

Why isn't "a.length > 0" an type-guard that help me Narrowing? #46638

aiden271828 opened this issue Nov 2, 2021 · 1 comment

Comments

@aiden271828
Copy link

aiden271828 commented Nov 2, 2021

Bug Report

πŸ”Ž Search Terms

array length narrowing

πŸ•— Version & Regression Information

  • This is a crash
  • This changed versions is 4.4.4

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const a:object[] = []
/**
* It can be 'push' 0 or multiple times.
* a[] is an array of arbitrary length
*/
a.push({});a.push({});a.push({});a.push({});a.push({});
while (a.length > 0) {
  // obj: object | undefined
  const obj = a.pop()
  // Object is possibly 'undefined'.
  console.log(obj.toString)
}

πŸ™ Actual behavior

Object is possibly 'undefined'.

I've obviously determined that the a [] length is greater than zero, which means pop cannot return undefined.

But TS is still telling me that obj might be undefined.I had to useconst obj = a.pop()! to make right.

Is this a bug or is ts not implemented?

If not implemented, Why didn't you do it(I'm very interested in it) ?

image

πŸ™‚ Expected behavior

obj type is not included undefined


@MartinJohns
Copy link
Contributor

Duplicate of #30406. Used search terms: array pop in:title

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants