JSMonk / hegel

An advanced static type checker
https://hegel.js.org
MIT License
2.09k stars 59 forks source link

Problem with booleans in if-else statement #183

Open vasilii-kovalev opened 4 years ago

vasilii-kovalev commented 4 years ago

It's actually hard to describe the problem in the title in couple of words. You can find the playground here.

  1. I found out the similar problem in TypeScript (link to the my comment in the issue). I'm not sure if it is a limitation of strong type checking or a bug. I extect true in "else" part since we already handle false in "if" part.
  2. In my TypeScript example I can see that type of field (on the top level of the result object) is true and field's type inside onClick function is boolean | undefined, but in the Hegel exemple both fields have boolean | undefined type. Which behavior is more correct?
ikabirov commented 4 years ago

simple repro https://hegel.js.org/try#C4TwDgpgBAkgdmArsKBeKBvAUFKAzASwgBsATALigH4AjAezuIgEM4BuHKVu4ACwgBOAMSJlKAZ2ACCcAOYcAvhyx5EcAMbACdOPgYAKUs2DMYwCAFtK8JMACUmTgTxR9AQgBCDJq0PHT5hYAdIQkpHZ2nNi4uAIQwIgCcJwKWJzqOpL4ohT0jCy66EYmZpYhOVgKQA

it's works if use dataItem.field === undefined || dataItem.field === false instead of !Boolean(dataItem.field)

vasilii-kovalev commented 4 years ago

@ikabirov, thanks for your example! Is it a common and expected practice to clarify the condition in such way to make strong typing work or it is just a temporal workaround?

ikabirov commented 4 years ago

Explicit is better than implicit. By it's just my opinion. cc @JSMonk

thecotne commented 4 years ago

for me x === true or x !== true is very good way to convert any value to boolean everything that's not true will become false (it matches Boolean constructors behavior for undefined and null but not for strings and numbers or arrays etc)

if you want true for everything that's not boolean you can use x !== false or x === false

function foo(value: ?boolean): boolean {
  if (value !== true) {
    return false
  }

  return value
}

try

JSMonk commented 4 years ago

Thank you a lot for your contribution ^_^. I will fix it soon.