繁体   English   中英

打字稿字符串到布尔值

[英]Typescript string to boolean

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

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

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

你可以做这样的事情,你可以有三个状态。 undefined表示该字符串不可解析为布尔值:

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'true'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;
}

这是单元测试:

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

TypeScript Recipe: Elegant Parse Boolean(参考原帖)

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

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

或者,您可以像在this answer to a similar SO question中那样使用switch语句。

如果你确定你有一个字符串作为输入,我建议如下。 例如在 Node 中使用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

我建议你希望 boolVar 为真,输入等于真,输入等于“真”(假相同),否则它应该是假的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM