将布尔值转换为字符串值

将布尔值转换为字符串值

本文介绍了TypeScript:将布尔值转换为字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题,我无法在TypeScript中将简单的布尔值转换为字符串值

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

我一直在漫游文档,我找不到任何有用的信息。当然,我尝试使用 toString()方法,但是它似乎并未在bool上实现。

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.

编辑:我几乎不了解JavaScript知识,并且具有C#/ Java背景的TypeScript。

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

推荐答案

TypeScript中的错误或明智的设计决策,但您可以使用以下方法来解决它:

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

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

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

这篇关于TypeScript:将布尔值转换为字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:26