0

I'm running into an issue when I'm trying to check if all of the properties in an object are populated and assigning the result to a boolean. This is the code:

this.isAddressValid = address.street && address.city && address.state && address.zip && address.country;

When I leave it like this, I get an error that states: Type 'string' is not assignable to type 'boolean'

But it seems to work if I add a simple conditional to the end:

this.isAddressValid = address.street && address.city && address.state && address.zip && address.country ? true : false;

I'm wondering why this is happening. Shouldn't the statement become a boolean by using the && operator? Why do I need to add the conditional for this to work?

2
  • 1
    "Shouldn't the statement become a boolean by using the && operator?" No. Moreover, it's trivial to check: console.log("hello" && "world") is not true but "world". Commented Jun 3, 2022 at 13:49
  • 2
    && returns the right-hand operand if it was truthy, otherwise the left-hand operand. So, 'a' && 'b' yields 'b', but '' && 'b' yields ''. (|| does the opposite.) Note that none of these are booleans, because at no point you converted something to a boolean. Most of the time this doesn't matter because you use the result with if or while, both of which care only about truthyness of the result and not actual equality with true. You can do !!(a && b && c) (or, more descriptively, Boolean(a && b && c)) if you want to convert the result (! does always return a boolean). Commented Jun 3, 2022 at 13:49

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.