You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
type narrowing, union type, conditional type, discriminated union, type inference
🕗 Version & Regression Information
This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing and discriminated unions.
⏯ Playground Link
No response
💻 Code
// Worked!functiontest1(value: {type: 'a'}|{type: 'b'}){if(value.type==='a'||value.type==='b'){}else{// @ts-expect-errorthrownewError(`asdf ${value.type}`)}}// Not Worked!functiontest2(value: {type: 'a'|'b'}){if(value.type==='a'||value.type==='b'){}else{// @ts-expect-errorthrownewError(`asdf ${value.type}`)}}
### 🙁ActualbehaviorIntest2,TypeScriptfailstonarrowthetypeofvaluewithintheifstatement,eventhoughtheconditionexplicitlychecksagainstallpossiblevaluesofvalue.type.Theelseblock,therefore,doesnotproduceatypeerror,despitelogicallybeingunreachable.The @ts-expect-errordirective is ignored.Thisisinconsistentwiththebehaviorintest1,wheretheequivalentlogicdoescorrectlynarrowthetype.Theonlydifferenceisthewaytheuniontypeisdefined: {type: 'a'}|{type: 'b'}versus{type: 'a'|'b'}.
### 🙂ExpectedbehaviorTypeScriptshouldconsistentlynarrowthetypeinbothtest1andtest2.Theelseblockintest2shouldproduceatypeerror,justasitdoesintest1,becausetheconditionensuresthattheelseblockislogicallyunreachable.The @ts-expect-errordirectiveshouldcorrectlyreflectthis.Thetypenarrowingbehaviorshouldnotdependonthesyntacticformoftheuniontypedefinition.
### AdditionalinformationabouttheissueThisinconsistencyleadstounpredictablebehaviorandreducesthereliabilityofTypeScript's type safety features. A consistent and predictable type narrowing mechanism is crucial for writing robust and maintainable code.
The text was updated successfully, but these errors were encountered:
🔎 Search Terms
type narrowing, union type, conditional type, discriminated union, type inference
🕗 Version & Regression Information
This is the behavior in every version I tried, and I reviewed the FAQ for entries about type narrowing and discriminated unions.
⏯ Playground Link
No response
💻 Code
The text was updated successfully, but these errors were encountered: