Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Convert a bool to string value

I have a really simple issue, I can't get to convert a simple boolean to a string value in TypeScript.

I have been roaming through documentation and I could not find anything helpful. 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.

like image 719
Ucodia Avatar asked Feb 08 '13 14:02

Ucodia


People also ask

Can we convert bool to string?

To convert Boolean to String in Java, use the toString() method. For this, firstly, we have declared two booleans. String str1 = new Boolean(bool1). toString(); String str2 = new Boolean(bool2).

How do you convert a boolean to a number in TypeScript?

Use the Number object to convert a boolean to a number in TypeScript, e.g. const num = Number(true) . When used as a function, Number(value) converts a value to a number. If the value cannot be converted, it returns NaN (not a number).

How do you assign a Boolean value to a variable in TypeScript?

Boolean values are supported by both JavaScript and TypeScript and stored as true/false values. TypeScript Boolean: let isPresent:boolean = true; Note that, the boolean Boolean is different from the lower case boolean type.


Video Answer


2 Answers

This is either a bug in TypeScript or a concious design decision, but you can work around it using:

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

In JavaScript booleans override the toString method, which is available on any Object (pretty much everything in JavaScript inherits from Object), so...

var myString: string = myBool.toString(); 

... should probably be valid.

There is also another work around for this, but I personally find it a bit nasty:

var myBool: bool = true; var myString: string = <string><any> myBool; alert(myString); 
like image 149
Fenton Avatar answered Sep 29 '22 08:09

Fenton


For those looking for an alternative, another way to go about this is to use a template literal like the following:

const booleanVal = true; const stringBoolean = `${booleanVal}`; 

The real strength in this comes if you don't know for sure that you are getting a boolean value. Although in this question we know it is a boolean, thats not always the case, even in TypeScript(if not fully taken advantage of).

like image 37
Jon Black Avatar answered Sep 29 '22 09:09

Jon Black