Ucodia
Ucodia

Reputation: 7700

TypeScript: Convert a bool to string value

I am unable to convert a boolean to a string value in TypeScript.

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

Upvotes: 147

Views: 221844

Answers (6)

Fenton
Fenton

Reputation: 250822

Updated for comments!

You can now use toString() to get a string value from a boolean type.

var myBool: boolean = true;
var myString: string = myBool.toString();
console.log(myString);

This outputs:

"true"

And has no errors or warnings.

Upvotes: 204

Pargat
Pargat

Reputation: 11

if you know your value is always true/false, you can use JSON.stringify(myBool) it will give you value like 'true' or 'false'

Upvotes: 1

priya veruva55
priya veruva55

Reputation: 31

return Boolean(b) ? 'true':'false'

Upvotes: 3

Jon
Jon

Reputation: 2671

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).

Upvotes: 51

Luca C.
Luca C.

Reputation: 12564

This if you have to handle null values too:

stringVar = boolVar===null? "null" : (boolVar?"true":"false");

Upvotes: 1

Tolga
Tolga

Reputation: 3695

One approach is to use the Ternary operator:

myString = myBool? "true":"false";

Upvotes: 25

Related Questions