TypeScript:将布尔值转换为字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14774907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:59:46  来源:igfitidea点击:

TypeScript: Convert a bool to string value

castingtype-conversiontypescript

提问by Ucodia

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

我有一个非常简单的问题,我无法在 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.

我一直在浏览文档,但找不到任何有用的东西,当然我尝试使用该toString()方法,但它似乎没有在 bool 上实现。



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

编辑:我几乎没有 JavaScript 知识,并以 C#/Java 背景来到 TypeScript。

回答by Fenton

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

这要么是 TypeScript 中的一个错误,要么是一个有意识的设计决策,但您可以使用以下方法解决它:

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

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

在 JavaScript 中,布尔值覆盖了该toString方法,该方法可用于任何Object(JavaScript 中的几乎所有内容都继承自Object),所以......

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

回答by Jon Black

For those looking for an alternative, another way to go about this is to use a template literallike 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).

如果您不确定您正在获得一个布尔值,那么这方面的真正优势就来了。尽管在这个问题中我们知道它是一个布尔值,但情况并非总是如此,即使在 TypeScript 中(如果没有充分利用)。

回答by Tolga

One approach is to use the Ternary operator:

一种方法是使用三元运算符:

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

回答by Luca C.

This if you have to handle null values too:

如果您也必须处理空值,请执行此操作:

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