flow icon indicating copy to clipboard operation
flow copied to clipboard

Boolean sentinel not correctly being checked

Open JohnyDays opened this issue 10 years ago • 8 comments

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!

JohnyDays avatar Dec 17 '15 11:12 JohnyDays

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

zgao avatar Dec 25 '15 19:12 zgao

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.)

samwgoldman avatar Dec 25 '15 19:12 samwgoldman

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

JohnyDays avatar Dec 26 '15 00:12 JohnyDays

type success = { A: string, success: void } would indicate that the success response doesn't have the key.

samwgoldman avatar Dec 26 '15 04:12 samwgoldman

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?

JohnyDays avatar Dec 27 '15 18:12 JohnyDays

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 }.

samwgoldman avatar Dec 27 '15 18:12 samwgoldman

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: !

JohnyDays avatar Dec 27 '15 18:12 JohnyDays

I was able to do this in the latest version, so closing.

JohnyDays avatar May 19 '16 16:05 JohnyDays