Repository navigation
aliasing discriminated union tag breaks case analysis #10830
Description
Activity
RyanCavanaugh commented
on Sep 9, 2016 MemberMore actionsThe type of a.t should correctly transfer to t when assigning or using destructuring. t should be usable as discriminant.
Tracking this correctly would require that variables "remember where they came from" and what implications that has on other variables. It'd probably be possible/reasonable to make that work at 1 level of indirection (rather than at 0 levels of indirection), but tracking it for N levels of indirection would be very complex, and then presumably you'd be surprised when it worked at 1 level of indirection but not 2.
So given the choice between "be surprised at 2 and things get way more complex in the compiler implementation" vs "be surprised at 1", we're generally sticking with the latter.
- addedToo ComplexAn issue which adding support for may be too complex for the value it addsAn issue which adding support for may be too complex for the value it adds
on Sep 9, 2016 What about the following case:
const { type, payload } = action; switch (type) { case 'SOME_STRING':
Is it too complex or there is possibility that you can add support for it?
Stefan Dobrev (@ligaz) this already works as intended:
declare const action: { type: "A", payload: number } | { type: "B", payload: string }; const { type, payload } = action; switch (type) { case 'SOME_STRING': // "SOME_STRING"" is not compatible with "A" | "B" }
The problem is that the payload is not typed if the tag is matched:
declare const action: { type: "A", payload: number } | { type: "B", payload: string }; const { type, payload } = action; switch (type) { case 'A': // payload type is 'number | string' not 'number'. }
- addedSuggestionAn idea for TypeScriptAn idea for TypeScript
on Sep 16, 2016 There is no way to know that there is a relationship between the two variables.
Reacted by Stefan Dobrev- locked and limited conversation to collaborators
on Jun 19, 2018 - addedFix AvailableA PR has been opened for this issueA PR has been opened for this issue
on Oct 8, 2021
TypeScript Version: 2.1.0-dev.20160909
Code
Expected behavior:
The type of
a.tshould correctly transfer totwhen assigning or using destructuring.tshould be usable as discriminant.Actual behavior:
The type of
tis widened from"a" | "b"tostringand therefore can not be used as discriminant any more.As the same happens also for flow (See facebook/flow#2409), it may be my thinking that is a little bit off. But I think that the case should be valid. The programmer should not be forced to repeat
base.all over, that’s what variables are for.