Closed
Description
π 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
π» 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
Labels
No labels