Skip to content

Fix non-null discriminant narrowing consistency - #64257

Open
S.H Jeong (z0rimo) wants to merge 2 commits into
microsoft:mainfrom
z0rimo:fix/discriminated-union-nullability-62511
Open

S.H Jeong (z0rimo) wants to merge 2 commits into
microsoft:mainfrom
z0rimo:fix/discriminated-union-nullability-62511

Conversation

@z0rimo

@z0rimo S.H Jeong (z0rimo) commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #62511

This fixes inconsistent nullability narrowing between small and large discriminated unions.

For example:

declare let small:
    | { type: "1" }
    | { type: "2" }
    | undefined;

if (small!.type === "1") {
    small.type; // 'small' is possibly 'undefined'
}

declare let large:
    | { type: "1" }
    | { type: "2" }
    | { type: "3" }
    | { type: "4" }
    | { type: "5" }
    | { type: "6" }
    | { type: "7" }
    | { type: "8" }
    | { type: "9" }
    | { type: "10" }
    | undefined;

if (large!.type === "1") {
    large.type; // Previously no error
}

Implementation

The constituent-map fast path introduced in #42556 can return the matching constituent directly, dropping nullable and void constituents that the general discriminant narrowing path retains.

This change preserves those constituents when present in the original union. It uses the existing containsType binary search rather than scanning the entire union, preserving type identity and keeping the lookup sublinear.

The change is limited to discriminant equality narrowing.

Behavioral changes

  • Non-null assertion narrowing is consistent between small and large nullable unions.
  • void constituents are preserved alongside null and undefined.
  • Comparisons such as x?.type === undefined retain the outer undefined when applicable.
  • Aliased optional-chain comparisons now follow the existing small-union behavior. This can reduce narrowing precision for stable aliases. Extending optional-chain containment through aliases is outside the scope of this change.

Direct optional-chain comparisons against non-undefined literal values retain their existing narrowing behavior in the tested cases.

Performance

The previous implementation performed a linear scan on constituent-map hits. The revised implementation performs a fixed number of binary searches, reducing the additional lookup cost from O(n) to O(log n).

Synthetic benchmark results (check time in milliseconds, median of seven runs):

Scenario Base Previous revision This revision
Non-nullable, 1,000 constituents 29 33 29
Non-nullable, 5,000 constituents 113 130 114
Undefined, 1,000 constituents 108 112 108
Undefined, 5,000 constituents 628 657 659
Null / void, 5,000 constituents 637 650 642
Optional chaining, 5,000 constituents 705 733 719

These measurements are from synthetic inputs designed to exercise repeated narrowing. They do not establish a performance improvement on real-world projects.

Tests

Added focused regression cases with diagnostic, type, and symbol baselines, and updated the existing narrowingUnionWithBang baseline.

The commit history separates the regression tests with pre-fix baselines from the implementation and corrected baselines.

npx hereby validate passes locally.

AI assistance was used during investigation and implementation. I reviewed the patch, traced the checker behavior, and verified the change with compiler tests, performance measurements, and the repository's validation commands locally.

Copilot AI balanced review requested due to automatic review settings September 14, 2026 01:55
@github-project-automation github-project-automation Bot moved this to Not started in PR Backlog Sep 14, 2026
@typescript-automation typescript-automation Bot added the For Backlog Bug PRs that fix a backlog bug label Sep 14, 2026
@z0rimo

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The implementation remains inconsistent for switch narrowing and can incorrectly narrow mutable values through aliased discriminants.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Fixes inconsistent nullability during discriminant narrowing after non-null assertions.

Changes:

  • Applies non-null facts before equality-based discriminant narrowing.
  • Adds small/large union regression tests.
  • Updates the affected type baseline.
File summaries
File Description
tsc/internal/checker/flow.go Normalizes nullable types before narrowing.
tsc/testdata/tests/cases/compiler/discriminatedUnionNonNullAccessNarrowing.ts Adds regression coverage.
tsc/testdata/baselines/reference/compiler/narrowingUnionWithBang.types Records corrected inferred types.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 2
  • Review effort level: Balanced

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

Comment thread tsc/internal/checker/flow.go Resolved
Comment thread tsc/internal/checker/flow.go Resolved
@z0rimo
S.H Jeong (z0rimo) marked this pull request as draft September 14, 2026 03:33
@z0rimo
S.H Jeong (z0rimo) marked this pull request as ready for review September 14, 2026 03:34
@z0rimo
S.H Jeong (z0rimo) requested a balanced review from Copilot September 14, 2026 03:59

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Combined non-null and optional-chain accesses incorrectly remove nullability from false and default branches.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (2)

tsc/internal/checker/flow.go:505

  • The mirrored right-hand form ("1" === value!?.type) has the same issue: optional chaining can complete with an undefined base, but this treats the base as non-null in both branches. Gate the eager non-null facts on the access not being an optional chain.
			if rightAccess == right && c.strictNullChecks && isNonNullAccess(rightAccess) && c.maybeTypeOfKind(t, TypeFlagsNullable) {

tsc/internal/checker/flow.go:1091

  • For switch (value!?.type), the default path can be reached because value is nullish. This condition nevertheless removes nullability for every switch clause because an optional access whose receiver is a non-null expression also satisfies isNonNullAccess. Exclude optional chains here so the existing switch optional-chain containment logic decides which clauses imply presence.
			if access == expr && c.strictNullChecks && isNonNullAccess(access) && c.maybeTypeOfKind(t, TypeFlagsNullable) {
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread tsc/internal/checker/flow.go Resolved
@z0rimo
S.H Jeong (z0rimo) marked this pull request as draft September 14, 2026 05:03
@z0rimo
S.H Jeong (z0rimo) marked this pull request as ready for review September 14, 2026 05:15
@z0rimo
S.H Jeong (z0rimo) requested a balanced review from Copilot September 14, 2026 05:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Eager non-null facts can become stale after assignments in later operands or switch case expressions.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

tsc/internal/checker/flow.go:1093

  • A switch discriminant is evaluated before its case expressions, and those expressions may reassign the matched reference. For example, switch (value!.type) { case (value = maybeUndefined, "1"): value.type; } can enter the case with value undefined, while this unconditional normalization drops that possibility. Account for writes from evaluated case labels before applying the eager fact (or restrict it to labels that cannot write the reference), and cover this ordering case in the regression test.
			if access == expr && c.strictNullChecks && !ast.IsOptionalChain(access) && isNonNullAccess(access) && c.maybeTypeOfKind(t, TypeFlagsNullable) {
				t = c.getTypeWithFacts(t, TypeFactsNEUndefinedOrNull)
			}
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread tsc/internal/checker/flow.go Resolved
@z0rimo
S.H Jeong (z0rimo) marked this pull request as draft September 14, 2026 05:31
@z0rimo
S.H Jeong (z0rimo) marked this pull request as ready for review September 14, 2026 05:41
@z0rimo
S.H Jeong (z0rimo) requested a balanced review from Copilot September 14, 2026 05:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Prefix assignments can invalidate dotted references while the new logic still applies an unsound non-null fact.

Get a fresh assessment by requesting another Copilot review.

Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread tsc/internal/checker/flow.go Resolved
@z0rimo
S.H Jeong (z0rimo) marked this pull request as draft September 14, 2026 05:47
@z0rimo
S.H Jeong (z0rimo) marked this pull request as ready for review September 14, 2026 05:58
@z0rimo
S.H Jeong (z0rimo) requested a balanced review from Copilot September 14, 2026 05:58

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Mutation scanning misses assertion-wrapped assignments and incorrectly scans deferred function bodies.

Review details

Suppressed comments (2)

Previously missed (2) — in code that hasn't changed since the last review.

tsc/internal/checker/flow.go:1862

  • Assignments whose target is wrapped in a type assertion are missed by this match. TypeScript permits (value as Small | undefined) = maybeUndefined; IsAssignmentTarget is true for the outer AsExpression, but isOrContainsMatchingReference does not unwrap that target. Consequently value!.type === ((value as Small | undefined) = maybeUndefined, "1") can remove undefined even though the true branch may run after assigning undefined. Please normalize assertion-wrapped assignment targets (including angle-bracket assertions) before matching and cover this form in the evaluation-order tests.
    tsc/internal/checker/flow.go:1865
  • This recursively scans deferred function bodies, so merely creating a closure on the right-hand side suppresses the new narrowing. For example, if (value!.type === (() => { value = undefined; }, "1")) { value.type } reports value as possibly undefined even though the assignment is never evaluated. Please traverse only code evaluated as part of the operand/case expression (while still handling invoked functions such as IIFEs) and add a regression case.
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Parenthesized assertions and synchronous assignments inside async IIFEs remain incorrectly handled.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tsc/internal/checker/flow.go:498

  • Parenthesizing the assertion still prevents the fix: for if ((value!).type === "1") value.type, isNonNullAccess returns false because it only recognizes an immediate NonNullExpression (tsc/internal/checker/utilities.go:1092-1094). The optimized path is then skipped for the still-nullable type and the fallback preserves undefined, even though parentheses are semantically transparent. Normalize parentheses around the access base in isNonNullAccess and add equality/switch coverage for this spelling.
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread tsc/internal/checker/flow.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The evaluation-order tests use small unions and therefore do not exercise the optimized path responsible for the stale-fact regression.

Get a fresh assessment by requesting another Copilot review.

Review details

Suppressed comments (1)

tsc/testdata/tests/cases/compiler/discriminatedUnionNonNullAccessNarrowing.ts:204

  • The switch evaluation-order regression is only exercised with Small, whose fallback narrowing was already conservative. Exercise this with Large so the test actually verifies that the optimized discriminant path no longer propagates the stale non-null fact through a mutating case expression.
declare let assignmentInCase: Small;
  • Files reviewed: 3/3 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Signed numeric and bigint discriminants remain incorrectly excluded from otherwise safe non-null narrowing.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

tsc/internal/checker/flow.go:1865

  • Signed numeric and bigint discriminants are incorrectly treated as side-effectful. For example, if (value!.type === -1) { value.type } and case -1 still retain undefined, because -1 is a PrefixUnaryExpression; with the new nullable guard, both paths fall back without applying the eager fact. Reuse the existing primitive-literal predicate, which includes side-effect-free signed literals, and add a signed-discriminant regression case.
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The implementation addresses union-size consistency and evaluation-order invalidation with comprehensive focused coverage.

Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

@z0rimo
S.H Jeong (z0rimo) marked this pull request as ready for review September 14, 2026 12:30
@z0rimo S.H Jeong (z0rimo) changed the title Fix non-null discriminant narrowing consistency and evaluation order Fix non-null discriminant narrowing consistency Sep 15, 2026
Comment thread tsc/internal/checker/flow.go Resolved
@github-project-automation github-project-automation Bot moved this from Not started to Waiting on author in PR Backlog Sep 16, 2026
@z0rimo

Copy link
Copy Markdown
Contributor Author

Ryan Cavanaugh (@RyanCavanaugh) I've reworked this based on your feedback. The fix no longer special-cases the non-null access syntax; nullable unions now fall back from the optimized discriminant-property paths to the existing general narrowing logic, for both equality and switch narrowing.

When you have a chance, could you take another look? Thanks!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The nullable restoration introduces a linear scan into the large-union fast path.

Review effort: Balanced
Findings: 1 Medium severity

Open (1)

Comment thread tsc/internal/checker/flow.go Resolved
@z0rimo
S.H Jeong (z0rimo) marked this pull request as ready for review September 30, 2026 11:00
@z0rimo

Copy link
Copy Markdown
Contributor Author

Hi Ryan Cavanaugh (@RyanCavanaugh), just following up on this PR.

The revised implementation removes the syntax-specific handling you pointed out and uses the existing general discriminant narrowing path for nullable unions.

I've also checked the performance concern raised in the subsequent review and documented the benchmark results above.

When you have a chance, could you take another look and let me know if the revised approach is acceptable?

Thanks!

@jakebailey

Copy link
Copy Markdown
Member

The commit history in this PR is pretty nonsensical. It would be best if you force pushed and replaced with one commit which adds the new test + "bad" baselines, then a fix commit which shows the change.

@z0rimo
S.H Jeong (z0rimo) force-pushed the fix/discriminated-union-nullability-62511 branch from d1844fe to d5824b7 Compare November 24, 2026 06:36
@z0rimo

Copy link
Copy Markdown
Contributor Author

The commit history in this PR is pretty nonsensical. It would be best if you force pushed and replaced with one commit which adds the new test + "bad" baselines, then a fix commit which shows the change.

Reworked the history into two commits: one adding the regression test with the failing baseline, followed by the fix and updated baselines. Thanks!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The narrowing logic still drops void and regresses aliased optional-chain narrowing, while tests lack coverage and baselines needed to verify the affected behavior.

4 open issues
1 resolved since last review

Review effort: Max

Comment thread tsc/internal/checker/flow.go Outdated
if assumeTrue && operator == ast.KindEqualsEqualsEqualsToken || !assumeTrue && operator == ast.KindExclamationEqualsEqualsToken {
return candidate
// Nullable constituents have no key property; preserve them as the general path does.
return c.getUnionType([]*Type{candidate, c.filterType(t, func(t *Type) bool { return t.flags&TypeFlagsNullable != 0 })})
Comment thread tsc/internal/checker/flow.go Outdated
if assumeTrue && operator == ast.KindEqualsEqualsEqualsToken || !assumeTrue && operator == ast.KindExclamationEqualsEqualsToken {
return candidate
// Nullable constituents have no key property; preserve them as the general path does.
return c.getUnionType([]*Type{candidate, c.filterType(t, func(t *Type) bool { return t.flags&TypeFlagsNullable != 0 })})
Comment thread tsc/internal/checker/flow.go Outdated
Comment on lines +710 to +711
// Nullable constituents have no key property; preserve them as the general path does.
return c.getUnionType([]*Type{candidate, c.filterType(t, func(t *Type) bool { return t.flags&TypeFlagsNullable != 0 })})
@@ -0,0 +1,35 @@
// @strict: true
// @noEmit: true
// @noTypesAndSymbols: true
@z0rimo
S.H Jeong (z0rimo) force-pushed the fix/discriminated-union-nullability-62511 branch from d5824b7 to 537de84 Compare November 25, 2026 01:54
@z0rimo

Copy link
Copy Markdown
Contributor Author

Updated the implementation to address the latest review feedback while keeping the two-commit structure.

The revised fix avoids a full union scan, and the updated PR description includes benchmark results and the remaining alias-narrowing trade-off.

Full validation passes locally.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

For Backlog Bug PRs that fix a backlog bug

Projects

Status: Waiting on author

Development

Successfully merging this pull request may close these issues.

Discriminated union with 11+ items does not handle nullability same as union with <10 items

4 participants