Open In App

How to Convert String to Boolean in TypeScript ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Typescript, sometimes you receive the data as strings but need to work with boolean values or identify the boolean equivalent of it.

There are several approaches to convert string to boolean in TypeScript which are as follows:

Using Conditional Statement

In this approach, we simply use a conditional statement to compare the input string with a boolean value (true/false). If the comparison returns true, that ensures the original string was `true`. In the case where the comparison does not return true, that means the original string was something other than `true`.

Syntax:

function stringToBoolean(str: string): boolean {
return str.toLowerCase() === 'true';
}

Example: TypeScript program defines stringToBoolean function converting a string to a boolean, exemplified by transforming ‘True’ to true and printing the result.

Javascript




function stringToBoolean(str: string): boolean {
    return str
        .toLowerCase() === 'true';
}
 
const result: boolean = stringToBoolean('True');
console.log(result);


Output

true

Using JSON.parse() Method

In this approach, we make the use of `JSON.Parse()` method to parse the string into its actual boolean form. But before parsing we makes sure that the string is converted into lowercase.

Syntax:

function stringToBoolean(str: string): boolean {
return JSON.parse(str.toLowerCase());
}

Example: This TypeScript program utilizes JSON parsing in the `stringToBoolean` function to convert a string to a boolean, demonstrated by transforming ‘False’ to `false` and displaying the result.

Javascript




function stringToBoolean(str: string): boolean {
    return JSON
     .parse(str.toLowerCase());
}
 
const result: boolean = stringToBoolean('False');
console.log(result);


Output

false

Using Type Assertion

In this approach, we use type assertion to explicitly declare the string as boolean. In this case also, we first need to convert the string into its lowercase.

Syntax:

function stringToBoolean(str: string): boolean {
return str.toLowerCase() as unknown as boolean;
}

Example: TypeScript program using the`stringToBoolean` function uses type assertion to convert a string to a boolean, demonstrated by transforming ‘true’ to `true` and displaying the result.

Javascript




function stringToBoolean(str: string): boolean {
    return str
        .toLowerCase() as unknown as boolean;
}
 
const result: boolean = stringToBoolean('true');
console.log(result);


Output

true


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads