Skip to content

Inappropriate Type Narrowing on Iterative Variable ReassignmentΒ #56216

Closed
@pedrodurek

Description

@pedrodurek

πŸ”Ž Search Terms

"type narrowing", "type narrowing within loop"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing.

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.2.2#code/FAFwngDgpgBAyiKEYF4YG9g2zAzoiAOQEMBbKALjxACcBLAOwHMscGoAPEBJKn5AD4wGAVwA2YgNzAAvsGABjAPYN81JABk6atAG0A5MX0AaGPoBGJswv0BdaWKggYACyjEAJvz4EYQ0RKowuJSwI7OEDRQAG7e8L7+IUEBocD4mtogAHQAZko0AKLECi4AFKXpRGRQAJSoAHwYrNjKqs7sAO5x-EGYOP3qVeTGzQPsXHEpo3KjdDkwpW6ePSirwRJ1fQPYS16+aJ380v0z-XMLkTH8m6P9l7EEWePc+8JQXQTHOKc49ytvHyQ0hkNXk4GgMEYOSgNCiHgAKpBYGhwVAlPNdvxgAB6bHYAB6AH5gEA

πŸ’» Code

type Step = {
    stepName: string
    nextStep: Step | null;
}

const stepList = ['a', 'b', 'c'];
let headStep: Step | null = null;
let prevStep: Step | null = null;

stepList.forEach((stepName) => {
    const newStep: Step = {
        stepName,
        nextStep: null
    }

    if (headStep === null) {
        headStep = newStep;
    }

    if (prevStep) {
        prevStep.nextStep = newStep;
    }

    prevStep = newStep;
})

type inferredType = typeof headStep
//  ^?

πŸ™ Actual behavior

type inferredType = typeof headStep
//  ^? type inferredType = null

πŸ™‚ Expected behavior

type inferredType = typeof headStep
//  ^? type inferredType = Step | null

Additional information about the issue

Whenever headStep is reassigned within the forEach loop, the Step gets filtered out from the original type (wrongly narrowing).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions