Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript conversion to boolean

Tags:

typescript

In Typescript I can do this:

var xxx : some_type;  if (xxx)     foo(); else     bar(); 

Here xxx will be treated as a boolean, regardless of its type.

I would like to do the same thing in a function argument. I have this function:

function foo(b : boolean) { ... } 

I want to be able to call foo(xxx) and have xxx treated as a boolean, regardless of its type. But Typescript won't allow that.

I tried this:

foo(<boolean>xxx); 

but that Typescript won't allow that either.

I can do this:

foo(xxx ? true : false); 

But that seems a bit silly. Is there a better way to do it?

like image 621
oz1cz Avatar asked Nov 20 '13 10:11

oz1cz


People also ask

How do I convert numbers to boolean in typescript?

Use the Boolean object to convert a value to a boolean in Typescript, e.g. Boolean(someValue) . When used as a function, the Boolean object converts the passed in value to a boolean - true if the value is truthy and false if it's a falsy value.

How convert string to boolean in typescript react?

The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true');

How do you convert to boolean?

Using parseBoolean() method of Boolean class This is the most common method to convert String to boolean. This method is used to convert a given string to its primitive boolean value. If the given string contains the value true ( ignoring cases), then this method returns true.

How do I convert a string to a number in typescript?

In typescript, there are numerous ways to convert a string to a number. We can use the '+' unary operator , Number(), parseInt() or parseFloat() function to convert string to number.


1 Answers

You can use double exclamation sign trick which Typescript does allow and which works fine in JavaScript:

foo(!!xxx); 

Alternatively, cast it to any

foo(<any>xxx); 
like image 134
Knaģis Avatar answered Nov 08 '22 09:11

Knaģis