TypeScript: Convert a bool to string value

送分小仙女□ 提交于 2019-12-12 10:32:39

问题


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 throught documentation and I could not find anything helpful 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.


回答1:


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



回答2:


One approach is to use the Ternary operator:

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



回答3:


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




回答4:


This if you have to handle null values too:

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


来源:https://stackoverflow.com/questions/14774907/typescript-convert-a-bool-to-string-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!