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?
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.
The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true');
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.
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.
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);
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