Typescript字符串为boolean

pan*_*nis 7 javascript typescript

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

let input = "true";
let boolVar = (input === 'true');
Run Code Online (Sandbox Code Playgroud)

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

Sar*_*ana 9

你可以做这样的事情,你可以有三种状态.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
Run Code Online (Sandbox Code Playgroud)

  • 如果字符串为大写,则不起作用。例如,“假”。因此, JSON.parse(input) 应该是 JSON.parse(input.toLowerCase()) (3认同)
  • 我一直在寻找执行此操作的内置函数,但似乎没有! (2认同)

am0*_*0wa 6

返回true, 1, , '1'不区分大小写)。否则true'true' false

function primitiveToBoolean(value: string | number | boolean | null | undefined): boolean {
  if (typeof value === 'string') {
    return value.toLowerCase() === 'true' || !!+value;  // here we parse to number first
  }

  return !!value;
}
Run Code Online (Sandbox Code Playgroud)

这是单元测试:

describe('primitiveToBoolean', () => {
  it('should be true if its 1 / "1" or "true"', () => {
    expect(primitiveToBoolean(1)).toBe(true);
    expect(primitiveToBoolean('1')).toBe(true);
    expect(primitiveToBoolean('true')).toBe(true);
  });
  it('should be false if its 0 / "0" or "false"', () => {
    expect(primitiveToBoolean(0)).toBe(false);
    expect(primitiveToBoolean('0')).toBe(false);
    expect(primitiveToBoolean('false')).toBe(false);
  });
  it('should be false if its null or undefined', () => {
    expect(primitiveToBoolean(null)).toBe(false);
    expect(primitiveToBoolean(undefined)).toBe(false);
  });
  it('should pass through booleans - useful for undefined checks', () => {
    expect(primitiveToBoolean(true)).toBe(true);
    expect(primitiveToBoolean(false)).toBe(false);
  });
    it('should be case insensitive', () => {
    expect(primitiveToBoolean('true')).toBe(true);
    expect(primitiveToBoolean('True')).toBe(true);
    expect(primitiveToBoolean('TRUE')).toBe(true);
  });
});
Run Code Online (Sandbox Code Playgroud)

TypeScript 配方:优雅的布尔解析(参考原帖)


Wha*_*ool 5

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

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

或者您可以使用 switch 语句,就像在类似的 SO 问题的答案中所做的那样


MG8*_*G83 -5

我建议您希望 boolVar 对于输入等于 true 且输入等于“true”(与 false 相同)为 true,否则它应该为 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 只要字符串不为空,`Boolean(input)` 将始终返回 true。所以你基本上只是在做“let boolVar = (input === 'true')”,这是首先的问题。即使它按照您期望的方式工作,但 false 和非布尔字符串之间仍然没有区别。 (2认同)