Typescript字符串为boolean [英] Typescript string to boolean

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

问题描述

我正在尝试将字符串转换为布尔值。有几种方法可以做到这一点
单程是

I am trying to convert a string to boolean. There are several ways of doing it one way is

let input = "true";
let boolVar = (input === 'true');

这里的问题是我必须验证输入是真还是假。而不是验证第一个输入然后进行转换是否有更优雅的方式?
在.NET中我们有 bool.TryParse 如果字符串无效则返回false。打字稿中是否有任何等价物?

The problem here is that I have to validate input if it is true or false. Instead of validating first input and then do the conversion is there any more elegant way? In .NET we have bool.TryParse which returns false if the string is not valid. Is there any equivalent in typescript?

推荐答案

你可以做这样的事情,你可以有三种状态。 undefined 表示该字符串不能解析为boolean:

You can do something like this where you can have three states. undefined indicates that the string is not parseable as boolean:

function convertToBoolean(input: string): boolean | undefined {
    try {
        return JSON.parse(input);
    }
    catch (e) {
        return undefined;
    }
}

console.log(convertToBoolean("true")); // true
console.log(convertToBoolean("false")); // false
console.log(convertToBoolean("invalid")); // undefined

这篇关于Typescript字符串为boolean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆