How to Convert String to Boolean in TypeScript ?
Last Updated :
04 Jul, 2024
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
Using Regular Expressions
In this approach, we employ regular expressions to match common boolean representations within the input string. By defining patterns for boolean values like "true", "false", "yes", "no", "1", and "0", we can accurately determine the boolean equivalent of the input string.
Syntax:
function stringToBoolean(str: string): boolean {
const truePattern: RegExp = /^(true|yes|1)$/i;
const falsePattern: RegExp = /^(false|no|0)$/i;
if (truePattern.test(str)) {
return true;
} else if (falsePattern.test(str)) {
return false;
} else {
throw new Error('Invalid boolean string');
}
}
Example: The following example demonstrates how to use regular expressions to convert a string to a boolean in TypeScript.
JavaScript
function stringToBoolean(str: string): boolean {
const truePattern: RegExp = /^(true|yes|1)$/i;
const falsePattern: RegExp = /^(false|no|0)$/i;
if (truePattern.test(str)) {
return true;
} else if (falsePattern.test(str)) {
return false;
} else {
throw new Error('Invalid boolean string');
}
}
const result1: boolean = stringToBoolean('True');
console.log(result1); // Output: true
const result2: boolean = stringToBoolean('no');
console.log(result2); // Output: false
Output:
true
false
Using a Map Object
In this approach, we use a Map object to store key-value pairs of string representations and their corresponding boolean values. This method provides a clean and efficient way to convert a string to a boolean by leveraging the Map object's get method.
Syntax:
function stringToBoolean(str: string): boolean {
const boolMap = new Map<string, boolean>([
['true', true],
['false', false],
['yes', true],
['no', false],
['1', true],
['0', false]
]);
const result = boolMap.get(str.toLowerCase());
if (result !== undefined) {
return result;
} else {
throw new Error('Invalid boolean string');
}
}
Example: This TypeScript program uses a Map object to convert a string to its boolean value, illustrated by transforming various strings and displaying the results.
JavaScript
function stringToBoolean(str: string): boolean {
const boolMap = new Map<string, boolean>([
['true', true],
['false', false],
['yes', true],
['no', false],
['1', true],
['0', false]
]);
const result = boolMap.get(str.toLowerCase());
if (result !== undefined) {
return result;
} else {
throw new Error('Invalid boolean string');
}
}
const result1: boolean = stringToBoolean('True');
console.log(result1); // Output: true
const result2: boolean = stringToBoolean('no');
console.log(result2); // Output: false
const result3: boolean = stringToBoolean('1');
console.log(result3); // Output: true
const result4: boolean = stringToBoolean('0');
console.log(result4); // Output: false
try {
const result5: boolean = stringToBoolean('maybe');
console.log(result5); // Output: Error
} catch (error: any) {
console.error(error.message);
}
Output:
true
false
true
false
Invalid boolean string
Similar Reads
How to Convert a Bool to String Value in TypeScript ?
When we talk about converting a boolean to a string value in TypeScript, we mean changing the data type of a variable from a boolean (true or false) to a string (a sequence of characters). We have multiple approaches to convert a bool to a string value in TypeScript. Example: let's say you have a va
4 min read
How to convert string to boolean in PHP?
Given a string and the task is to convert given string to its boolean. Use filter_var() function to convert string to boolean value. Examples: Input : $boolStrVar1 = filter_var('true', FILTER_VALIDATE_BOOLEAN); Output : true Input : $boolStrVar5 = filter_var('false', FILTER_VALIDATE_BOOLEAN); Output
2 min read
How to convert String to Boolean in Ruby?
In this article, we will learn how to convert string to Boolean in Ruby using various methods. Letâs understand each of them with the help of examples. Table of Content Converting string to Boolean using String#casecmpConverting string to Boolean using String#downcaseConvert string to Boolean using
3 min read
How to Format Strings in TypeScript ?
Formatting strings in TypeScript involves combining and structuring text to produce clear and readable output. This practice is essential for creating dynamic and user-friendly applications, as it allows developers to seamlessly integrate variables and expressions into strings, enhancing the overall
3 min read
How to convert Number to Boolean in JavaScript ?
We convert a Number to Boolean by using the JavaScript Boolean() method and double NOT operator(!!). A JavaScript boolean results in one of two values i.e. true or false. However, if one wants to convert a variable that stores integer â0â or â1â into Boolean Value i.e. "false" or "true". Below are
2 min read
How to Filter Keys of Type string[] in TypeScript ?
In TypeScript, the filtering of keys of type string[] can be done by iterating over the data object, and applying the condition to the string if the key is a string. If the condition is satisfied, then an array of output results is created which consists of filtered keys of type string[]. The below
3 min read
How to Declare an Array of Strings in TypeScript ?
Arrays are fundamental data structures in TypeScript, enabling developers to manage collections of elements efficiently. Below are the approaches to declare an Array of strings in TypeScript: Table of Content Square Brackets NotationArray ConstructorSquare Brackets NotationUsing square brackets nota
1 min read
How to Convert a Dictionary to an Array in TypeScript ?
In TypeScript, converting a dictionary(an object) into an Array can be useful in scenarios where you need to work with the values in a more iterable and flexible manner. These are the following approaches: Table of Content Using Object.keys methodUsing Object.values methodUsing Object.entries method
3 min read
How to Create an Enum With String Values in TypeScript ?
To create an enum with string values in TypesScript, we have different approaches. In this article, we are going to learn how to create an enum with string values in TypesScript. Below are the approaches used to create an enum with string values in TypesScript: Table of Content Approach 1: Using Enu
3 min read
How to Restrict a Number to a Certain Range in TypeScript ?
Restricting a number to a certain range in TypeScript means ensuring that a numerical value falls within specific bounds or limits. This process, often referred to as "clamping" or "bounding," prevents a number from going below a minimum value or exceeding a maximum value. For example, if you have a
2 min read