How to use Conditional Statement In Typescript
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.
function stringToBoolean(str: string): boolean {
return str
.toLowerCase() === 'true';
}
const result: boolean = stringToBoolean('True');
console.log(result);
Output
true
How to Convert String to Boolean in TypeScript ?
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:
Table of Content
- Using Conditional Statement
- Using JSON.parse() Method
- Using Type Assertion
- Using Regular Expressions