Javascript 打字稿字符串到布尔值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44024193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript string to boolean
提问by pantonis
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');
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.TryParsewhich returns false if the string is not valid. Is there any equivalent in typescript?
这里的问题是我必须验证输入是对还是错。有没有更优雅的方法,而不是验证第一个输入然后进行转换?在 .NET 中bool.TryParse,如果字符串无效,则返回 false。打字稿中有任何等价物吗?
回答by Saravana
You can do something like this where you can have three states. undefinedindicates that the string is not parseable as boolean:
你可以做这样的事情,你可以有三个状态。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
回答by am0wa
Convert 1'1'and 'true'to trueand 0'0''false'nulland undefinedto false
转换1'1'并'true'以true和0'0''false'null和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;
}
Here is Unit test:
这是单元测试:
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);
});
});
TypeScript Recipe: Elegant Parse Boolean (ref. to original post)
回答by What Would Be Cool
You could also use an array of valid values:
您还可以使用一组有效值:
const toBoolean = (value: string | number | boolean): boolean =>
[true, 'true', 'True', 'TRUE', '1', 1].includes(value);
Or you could use a switch statement as does in this answer to a similar SO question.
或者,您可以像在this answer to a similar SO question中那样使用switch语句。
回答by MG83
I suggest that you want boolVar to be true for input equals true and input equals "true" (same for false) else it should be false.
我建议你希望 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;
}

