So I have the following code:
type Something =
| { t: 'A', src: string }
| { t: 'B', src: string }
| { t: 'C', src: number };
const f = (o: Something): string =>
o.t === 1
? o.src
: 'a-string';
I expect to see an error when I return o.src when o.t is 1 since I never defined that t can be a number. Therefore, flow doesn't know what the type of o.src is if the t is number. But it works without any error. What am I missing here?
Here is the flow/try.
For the record, the TypeScript version throws an error correctly. Though the error message is not so useful.
To clarify a bit more, if I use o.t === 'F' instead, then flow will happily throw the following error:
9: o.t === 'F' ^ all branches are incompatible: Either object with property
tthat matches string literalF1 is incompatible with string literalA2. Or object with propertytthat matches string literalF1 is incompatible with string literalB[3]. Or object with propertytthat matches string literalF1 is incompatible with string literalC[4]. References: 9: o.t === 'F' ^ 1 4: | { t: 'A', src: string } ^ 2 5: | { t: 'B', src: string } ^ [3] 6: | { t: 'C', src: number }; ^ [4]
I don't know why, but it's just not consistent behavior and I expect to see some error if I'm using a value that not defined in the type. You know, like an unreachable piece of code.