Given this typescript (2.7.2) interface:
export interface A {
b?: string;
c?: boolean;
}
This will print boolean 'false' as expected:
let a: A = {b: ''};
if (a.b && a.b.length > 0) {
a.c = true;
} else {
a.c = false;
}
console.log(a.c);
However, this prints an empty '' string:
let a: A = {b: ''};
a.c = a.b && a.b.length > 0;
console.log(a.c);
I'm a bit confused here. The second example should behave like the first one, right? What am I missing?
a.b && a.b.length > 0 which is equivalent to "" && false because empty string evaluates falsy. Expression "" && false evaluates to "". that is why a.c is "".
Refactor it like this,
a.c = a.b && a.b.length > 0 ? true : false
This is more of a Javascript truthy/falsy issue. The && operator will return the value of one of the operands. See docs:
However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.
And specifically for && :
Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
In your case "" is a falsy value, so it can be converted to false. If you want to ensure you get a boolean use !! (ie. double negation)
let a: A = {b: ''};
a.c = !!(a.b && a.b.length > 0);
console.log(a.c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With