TypeScript: convert bool value to string value

I have a really simple problem, I cannot go to convert a simple boolean value to a string value in TypeScript.

I was looking through all the documentation and I could not find anything useful, and of course I tried to use the toString() method, but it does not seem to be implemented on bool.




Edit: I have almost no JavaScript knowledge and came to TypeScript with a C # / Java background.

+16
casting type-conversion typescript
Feb 08 '13 at 14:37
source share
2 answers

This is either a TypeScript error or a reasonable design decision, but you can work around it using:

 var myBool: bool = true; var myString: string = String(myBool); alert(myString); 

In JavaScript, booleans overrides the toString method, which is available for any Object (almost everything in JavaScript inherits from Object ), so ...

 var myString: string = myBool.toString(); 

... likely to be valid.

There is another work for this, but I personally find it a little nasty:

 var myBool: bool = true; var myString: string = <string><any> myBool; alert(myString); 
+30
Feb 08 '13 at 16:34
source share

One approach is to use the Ternary operator:

 myString = myBool? "true":"false"; 
+1
Dec 30 '17 at 2:05
source share



All Articles