How can I convert a string to a boolean in TypeScript for an Angular 4 application?

How can I convert a string to a boolean in TypeScript for an Angular 4 application?

I am working with local storage to store and retrieve boolean values as strings. Here’s how I’m doing it:

In app.component.ts: localStorage.setItem('CheckOutPageReload', this.btnLoginNumOne + ',' + this.btnLoginEdit);

Here, this.btnLoginNumOne and this.btnLoginEdit are string values, either “true” or “false”.

In mirror.component.ts, I retrieve and process these values:

if (localStorage.getItem('CheckOutPageReload')) {
    let stringToSplit = localStorage.getItem('CheckOutPageReload');
    this.pageLoadParams = stringToSplit.split(',');

    this.btnLoginNumOne = this.pageLoadParams[0]; // Error: boolean value is not assignable to string
    this.btnLoginEdit = this.pageLoadParams[1]; // Error: boolean value is not assignable to string
}

In this component, this.btnLoginNumOne and this.btnLoginEdit are expected to be boolean values.

I have tried various solutions, but none have worked. How can I correctly convert the string values from local storage to boolean values in TypeScript? Please provide guidance on how to handle this conversion using the keyword typescript string to boolean.

Hi Neha,

Method 1: Using Regular Expressions

var stringValue = "true";
var boolValue = (/true/i).test(stringValue); // returns true

Method 2: Simple Comparison

var stringValue = "true";
var boolValue = (stringValue == "true");   // returns true

Method 3: Using JSON.parse

var stringValue = "true";
var boolValue = JSON.parse(stringValue);   // returns true

Method 4: Case-Insensitive Comparison

var stringValue = "true";
var boolValue = stringValue.toLowerCase() == 'true'; // returns true

Method 5: Using a Custom Function

var stringValue = "true";
var boolValue = getBoolean(stringValue); // returns true

function getBoolean(value) {
   switch(value) {
        case true:
        case "true":
        case 1:
        case "1":
        case "on":
        case "yes":
            return true;
        default:
            return false;
    }
}