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.TryParse
which returns false if the string is not valid. Is there any equivalent in typescript?
To convert a string to a boolean in TypeScript, use the strict equality operator to compare the string to the string "true" , e.g. const bool = str === 'true' . If the condition is met, the strict equality operator will return the boolean value true , otherwise false is returned. Copied!
String str = "false"; Now, use the Boolean. parseBoolean() method to convert the above declared String to Boolean.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With