|
|
|
|
|
by davorak
477 days ago
|
|
Maybe I am doing something wrong but when I fill in a concrete value for `aOrB` I still get a type error in that example code: Playground Link: https://www.typescriptlang.org/play/?#code/C4TwDgpgBAglC8UDe... I tried with 5.8.2 and nightly and the results were the same. Interestingly, the playground reports aOrB(from github comment with concrete value) and aOrB2(modified) as the same type, `A | B`, but aOrB will give an error in the typeguarded if block but aOrB2 does not trigger an error. I do not know what is going on there either they do not really have the same type despite the playground reporting both as `A | B` or there is different bug going on. So the solution presented in github does not look like a full solution as is. |
|
It would make more sense for TS to treat the body of the if-statement as unreachable and give a warning based on that, but I guess they figured that this kind of thing - doing a type guard on a value that is already known to be of a different type - is a very narrow corner case that isn't worth improving diagnostics for.
I'm more curious about why "smuggling" it through an array makes it work. In that case, the type of `aOrB2` remains `A | B` in the conditional, so everything is working as you expected, but I don't see the fundamental difference between this case and the previous one...