Parse String to Boolean using JSON.parse()

JSON.parse() is able to convert a string to boolean easily while retaining its value.


_10
let strTrue = "true";
_10
let strFalse = "false";
_10
_10
console.log(JSON.parse(strTrue)); // true
_10
console.log(JSON.parse(strFalse)); // false

While working on environment variables using process.env from a .env file, I realised that I had to use strict equal process.env.SOME_VARIABLE === "true" in order to make the condition as a valid boolean since environment variables are typeof String. While finding a better way around this, I came across using the JSON.parse() way that seems to make it easier. I was able to write a reusable function to make things easier for me too.

.env

_10
SOME_VARIABLE=true


_10
const isFeatureEnabled = (feature: string): boolean => {
_10
return JSON.parse(feature);
_10
};
_10
_10
isFeatureEnabled(process.env.SOME_VARIABLE); // true

Let me know how other ways do you handle converting a string of values "true" or "false" to their boolean values.