Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript assigns an empty string instead of a boolean

Tags:

typescript

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?

like image 329
saimonsez Avatar asked Dec 10 '25 17:12

saimonsez


2 Answers

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
like image 87
Anurag Awasthi Avatar answered Dec 13 '25 08:12

Anurag Awasthi


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);
like image 40
Titian Cernicova-Dragomir Avatar answered Dec 13 '25 09:12

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!