Fix: Make discriminant property selection order-independent in unions (#62512) #62516
+401
−10
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix: Make discriminant property selection order-independent in unions
Summary
This PR fixes an issue where TypeScript's narrowing for discriminated unions depended on the order of union members. Previously, the compiler would select the first property with a unit (literal) type as the discriminant, which could lead to incorrect narrowing and inconsistent behavior based on type order.
Related Issue
Fixes #62512 (Type checking of discriminated nullable union depends on type order)
Approach
getKeyPropertyName
function to scan all union members and select the most common unit-typed property as the discriminant, rather than picking the first one found.Tests
discriminantOrderIndependence.ts
to demonstrate and verify order-independence for discriminant selection.discriminantOrderIndependence.js
discriminantOrderIndependence.types
discriminantOrderIndependence.symbols
Notes
Thank you for reviewing!