Boolean sentinel not correctly being checked
Maybe there's a better title for this, but from my limited understanding of flow, that's what I could come up with. The problem is the following:
type success = { A: string }
type error = { B: string, success: false }
type response = success | error
const result: response = global.anyMethod()
if (result.success === false) {
console.log(result.B) //Errors when it shouldn't
}
8: console.log(result.B)
^ property `B`. Property not found in
4: type response = success | error
^^^^^^^ object type
Found 1 error
Am i missing something obvious? This isn't a 0.20 problem, I had it before upgrading from 0.19, I'm actually on a current master built version though. Thanks a bunch for flow, i've been using it in all my new projects and i'm never looking back. Cheers!
Hypothesis: perhaps you would have to put success: true in A? Otherwise some result like { A: 'test', success: false } would fall into type success, since it says nothing about the value of success
Boolean sentinels is a TODO (#577), but in this example, due to subtyping, that response type isn't sufficient for discrimination on the success property. As a counter example, the following statement is legal given the above declarations.
var r: response = { A: "hi", success: false }
(That is to say, @zgao is 100% correct. Unfortunately, adding success: true on the success type is insufficient until #577 is resolved.)
Cool! I'll track that issue to look out for it. But how would you model this case, where an error response MUST have { success: false } but a successful response doesn't have the key at all? This is pretty common, at least with most apis I've used
type success = { A: string, success: void } would indicate that the success response doesn't have the key.
Does that type definition not mean that the key is there, but it has a null value?
EDIT: Is { success: undefined } a valid definition for this case?
Well, you could try it and see, but I realize I've misled you a bit. void is the type of undefined, but if you want to allow omitting the key entirely you need to use the optional object property syntax, e.g. { success?: void }.
Cool, I was under the impression that void was null. I'll try that out when I'm back at work, regardless I'll have to wait for #577. Thanks again :+1: !
I was able to do this in the latest version, so closing.