Why doesn't typescript object made up of false values return false? Otherwise how can I make it?

538 views Asked by At

I have the following object:

const obj = {valueOne: false, valueTwo: false, valueThree: false}

and

console.log(obj) 
console.log(Boolean(obj))
// true
// true

One would think console.log(Boolean(obj) would return false but it doesn't? Is there any way to return the overall truthiness of the object without evaluating each field?

So basically I'd like a short hand version of the following:

if (obj.valueOne || obj.valueTwo || object.valueThree){
return true
}else{
return false
}
1

There are 1 answers

0
Quentin On

One would think console.log(Boolean(obj) would return false but it doesn't?

No. The specification says that when you convert an object to a boolean, you get true. That's unconditional. It doesn't matter what values the properties of the object has.

Is there any way to return the overall truthiness of the object without evaluating each field?

Not really.

You could extract the values and search for one that is truthy.

const obj = {
  valueOne: false,
  valueTwo: false,
  valueThree: false
}
const anyTruthy = Object.values(obj).some(value => value);
console.log(anyTruthy);

… and that will stop as soon as it finds one that matches, but you'll have to search through them all to confirm that none of them do. It does save you from having to name each property explicitly.