155

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

I have tried to use the toString() method but it does not seem to be implemented on bool.

2
  • 2
    That's odd, the native JS Boolean supports toString. Commented Feb 8, 2013 at 15:36
  • 1
    It seems that TypeScript definitely misses this basic implementation. Commented Feb 8, 2013 at 15:50

6 Answers 6

209

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This is an acknowledged bug in TypeScript and is apparently planned to be fixed in the next release (0.8.2) - typescript.codeplex.com/workitem/362
toString() will definitely work fine as of 2016 (versions 1.6)
flag: boolean = Boolean("true"); if you need to convert to boolean from string
Apparently even for TS Version 2.9.0-dev.20180327 toString() will definitely NOT work! Had to use @Fenton's example here for it to work. WEIRD but fact.
In TypeScript 5.6.2, the following is valid: ${myBool.toString().toUpperCase()}.
53

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

Comments

27

One approach is to use the Ternary operator:

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

1 Comment

One advantage of this approach is the converted string becomes literal types of "true" | "false"
3
return Boolean(b) ? 'true':'false'

2 Comments

While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: stackoverflow.com/help/how-to-answer . Good luck 🙂
If b is already a boolean, why use Boolean(b)?
1

This if you have to handle null values too:

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

Comments

1

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

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.