Skip to content

Type Narrowing Inside Looping Structure Conditions not PersistingΒ #54660

Closed as not planned
@xXCrash2BomberXx

Description

@xXCrash2BomberXx

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions