How to convert string to boolean in typescript Angular 4

AngularTypescriptAngular Local-Storage

Angular Problem Overview


I know am not the first to ask this and as I mentioned in my title ,I am trying to convert string value boolean .

I have previously put some values into local storage,Now I want to get all the values and assign all to the some boolean variables .

app.component.ts

localStorage.setItem('CheckOutPageReload', this.btnLoginNumOne + ',' + this.btnLoginEdit);

here this.btnLoginNumOne and this.btnLoginEdit are string values ("true,false").

mirror.component.ts

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

      this.btnLoginNumOne = this.pageLoadParams[0]; //here I got the error as boolean value is not assignable to string
      this.btnLoginEdit = this.pageLoadParams[1]; //here I got the error as boolean value is not assignable to string
}

in this component this.btnLoginNumOne and this.btnLoginEdit are Boolean values;

I tried the solutions in stackoverflow but nothing is worked.

Can anyone help me to fix this .

Angular Solutions


Solution 1 - Angular

Method 1 :

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

Method 2 :

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

Method 3 :

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

Method 4 :

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

Method 5 :

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;
    }
}

source: http://codippa.com/how-to-convert-string-to-boolean-javascript/

Solution 2 - Angular

I have been trying different values with JSON.parse(value) and it seems to do the work:

// true
Boolean(JSON.parse("true"));
Boolean(JSON.parse("1"));
Boolean(JSON.parse(1));
Boolean(JSON.parse(true));

// false
Boolean(JSON.parse("0")); 
Boolean(JSON.parse(0));
Boolean(JSON.parse("false"));
Boolean(JSON.parse(false));

Solution 3 - Angular

In your scenario, converting a string to a boolean can be done via something like someString === 'true' (as was already answered).

However, let me try to address your main issue: dealing with the local storage.

The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.

A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.

The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.

function setItemInStorage(key, item) {
  localStorage.setItem(key, JSON.stringify(item));
}

function getItemFromStorage(key) {
  return JSON.parse(localStorage.getItem(key));
}

Your example could then be rewritten as:

setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);

And:

const pageLoadParams = getItemFromStorage('CheckOutPageReload');
if (pageLoadParams) {
  this.btnLoginNumOne = pageLoadParams[0];
  this.btnLoginEdit = pageLoadParams[1];
}

Solution 4 - Angular

Define extension: String+Extension.ts

interface String {
  toBoolean(): boolean
}

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

And import in any file where you want to use it '@/path/to/String+Extension'

Solution 5 - Angular

This function will convert your string to boolean

export const stringToBoolean = (str: string | null | undefined) => {
    if (!str) {
	    return false
    }
    if (typeof str === "string") {
	    return !["0", "false", "no", "n", "null", "undefined", "nil"].includes(str.toLowerCase().trim())
    }
    return Boolean(str)
}

Solution 6 - Angular

I think this is most accurate:

function parseBoolean(value?: string | number | boolean | null) {
    value = value?.toString().toLowerCase();
    return value === 'true' || value === '1';
}

Solution 7 - Angular

just use << !! >> operator:

const Text1 = ""
const Text2 = "there is a text"

console.log(!!Text1) // false
console.log(!!Text2) // true

Solution 8 - Angular

You can use that:

let s: string = "true";
let b: boolean = Boolean(s);

Solution 9 - Angular

You could also try using the bang bang operator if you know its a valid boolean value in the string. for e.g.

let trueAsString = 'true';

let convertedStringToBool = !!trueAsString;

Solution 10 - Angular

Boolean("true") will do the work too

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZhuView Question on Stackoverflow
Solution 1 - AngularAyoub kView Answer on Stackoverflow
Solution 2 - AngularGonzaloView Answer on Stackoverflow
Solution 3 - AngularnunocastromartinsView Answer on Stackoverflow
Solution 4 - AngularRenetikView Answer on Stackoverflow
Solution 5 - AngularValentin NasratyView Answer on Stackoverflow
Solution 6 - AngularXzaRView Answer on Stackoverflow
Solution 7 - AngularChadjaa SofianneView Answer on Stackoverflow
Solution 8 - AngularKevin LetoView Answer on Stackoverflow
Solution 9 - AngularIronWorkshopView Answer on Stackoverflow
Solution 10 - AngularIshaiView Answer on Stackoverflow