TypeScript中将字符串转换为布尔值的四种方法

本 Typescript 教程介绍了如何使用四种不同的方法在 Typescript 中将字符串转换为布尔值:

方法一:使用比较
在 Typescript 中将字符串转换为 bool 最简单的方法是将字符串与 或 直接进行比较

function stringToBoolean(str: string): boolean {
  return str === "true";
}
console.log(stringToBoolean(
"true"));
console.log(stringToBoolean(
"false"));

方法 2:布尔构造函数
TypeScript 允许使用布尔构造函数,但有一个警告。它将非空字符串转换为true,将空字符串转换为false. 这是 Typescript 中字符串到布尔值的完整示例。

function stringToBoolean(str: string): boolean {
  return Boolean(str);
}
console.log(stringToBoolean("hello"));
console.log(stringToBoolean(
""));

方法 3:使用三元运算符
要更好地控制哪些字符串转换为trueor false,请在 Typescript 中使用三元运算符。以下是“Typescript 将字符串转换为布尔值”的示例,包含完整代码:

function stringToBoolean(str: string): boolean {
  return (str.toLowerCase() === "true") ? true : false;
}
console.log(stringToBoolean(
"True"));
console.log(stringToBoolean(
"FALSE"));

方法 4:使用 Switch Case
您还可以在 Typescript 中使用 switch case 将字符串转换为布尔值。在处理多个 true 或 false 字符串表示形式时,此方法非常有用。这是一个例子。

function stringToBoolean(str: string): boolean {
  switch(str.toLowerCase()) {
      case "true":
      case
"yes":
      case
"1":
          return true;
      case
"false":
      case
"no":
      case
"0":
          return false;
      default:
          throw new Error(
"Invalid input");
  }
}
console.log(stringToBoolean(
"yes"));
console.log(stringToBoolean(
"0"));

结论
在 TypeScript 中将字符串转换为布尔值可以通过多种方法来实现,每种方法都有自己的用例。