Parse String to Boolean using JSON.parse()
JSON.parse()
is able to convert a string to boolean easily while retaining its value.
_10let strTrue = "true";_10let strFalse = "false";_10_10console.log(JSON.parse(strTrue)); // true_10console.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.
_10const isFeatureEnabled = (feature: string): boolean => {_10 return JSON.parse(feature);_10};_10_10isFeatureEnabled(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.