Typescript字符串为boolean

时间:2017-05-17 11:56:59

标签: javascript typescript

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

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

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

5 个答案:

答案 0 :(得分:8)

你可以做这样的事情,你可以有三种状态。 undefined表示该字符串不能解析为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

答案 1 :(得分:1)

1 '1''true'转换为true0 '0' 'false' null和{{ 1}}到undefined

false

这是单元测试:

function primitiveToBoolean(value: string | number | boolean | null | undefined): boolean {
  if (value === 'true') {
    return true;
  }

  return typeof value === 'string'
    ? !!+value   // we parse string to integer first
    : !!value;
}

TypeScript Recipe: Elegant Parse Boolean (ref. to original post)

答案 2 :(得分:0)

您还可以使用有效值数组:

const toBoolean = (value: string | number | boolean): boolean => 
    [true, 'true', 'True', 'TRUE', '1', 1].includes(value);

或者您可以像in this answer to a similar SO question一样使用switch语句。

答案 3 :(得分:0)

如果您确定输入的是字符串,则建议以下内容。例如,在节点{p> 1中使用process.env检索环境变量时,可能就是这种情况。

function toBoolean(value?: string): boolean {
  if (!value) {
    //Could also throw an exception up to you
    return false
  }

  switch (value.toLocaleLowerCase()) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

https://codesandbox.io/s/beautiful-shamir-738g5?file=/src/index.ts

答案 4 :(得分:-5)

我建议您希望boolVar为true,输入等于true,输入等于“true”(同样为false),否则应该为false。

let input = readSomeInput(); // true,"true",false,"false", {}, ...
let boolVar = makeBoolWhateverItIs(input);

function makeBoolWhateverItIs(input) {
    if (typeof input == "boolean") {
       return input;
    } else if typeof input == "string" {
       return input == "true";  
    }
    return false;
}