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

Type Narrowing Inside Looping Structure Conditions not Persisting #54660

Closed
xXCrash2BomberXx opened this issue Jun 15, 2023 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@xXCrash2BomberXx
Copy link

xXCrash2BomberXx commented Jun 15, 2023

Bug Report

πŸ”Ž Search Terms

Looping, Condition, Inference, Chain, And, &&, Array

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Type Guards

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

let arr: Array<Array<boolean> | number> = [[true]];

for (let i = 0; i < arr.length; i++)
    if (arr[i] instanceof Array && arr[i].length > 0)  // Property 'length' does not exist on type 'number | boolean[]'.
        console.log(arr[i].length);  // Property 'length' does not exist on type 'number | boolean[]'.

if (arr[0] instanceof Array && arr[0].length > 0)
    console.log(true);

πŸ™ Actual behavior

When attempting to compile, the condition arr[i] instanceof Array infers that arr[i] is an Array and has the property length but this inference is not continued throughout the rest of the condition nor body within the condition due to the variable i. This behavior does not match the behavior with a fixed-index as is shown in the fixed-index block.

πŸ™‚ Expected behavior

Ideally, the inference from arr[i] instanceof Array would be continued into arr[i].length > 0 due to it being an && which makes the second condition never run unless arr[i] is an instance of Array. This should also be the case for the body of the if statement. This behavior is shown with a fixed index but does not apply to a variable one.

@fatcerberus
Copy link

It has nothing to do with the loop. It's just that obj[key] isn't narrowed when key is not a literal. Duplicate of #51368 -> #10530

@fatcerberus
Copy link

fatcerberus commented Jun 15, 2023

Workaround: First assign the value of arr[i] to a variable inside the loop and narrow that.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jun 19, 2023
@typescript-bot
Copy link
Collaborator

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

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants