Loading...

How to parse string to boolean in Typescript?

question typescript
Ram Patra Published on November 21, 2024

In TypeScript, parsing a string to a boolean typically involves converting specific string values (e.g., "true" or "false") to their corresponding boolean values. Here’s how you can do it:

Example 1: Basic Parsing

const parseBoolean = (value: string): boolean => {
  return value.toLowerCase() === "true";
};

// Usage
console.log(parseBoolean("true")); // Output: true
console.log(parseBoolean("false")); // Output: false
console.log(parseBoolean("TRUE")); // Output: true

Example 2: Safer Parsing with Validation

To handle invalid values gracefully:

const parseBooleanSafe = (value: string): boolean | null => {
  const lowerValue = value.toLowerCase();
  if (lowerValue === "true") return true;
  if (lowerValue === "false") return false;
  return null; // Return null for invalid input
};

// Usage
console.log(parseBooleanSafe("true")); // Output: true
console.log(parseBooleanSafe("false")); // Output: false
console.log(parseBooleanSafe("not-boolean")); // Output: null

Notes:

  • toLowerCase() ensures case insensitivity.
  • Returning null or throwing an error for invalid input is a good practice to avoid unexpected behavior.
  • If the string isn’t strictly "true" or "false", it won’t match a boolean value.

Choose the approach that aligns with your application’s needs!

Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on November 21, 2024
Image placeholder

Keep reading

If this article was helpful, others might be too

question typescript July 28, 2024 Interface vs Type alias in Typescript with some real-world examples showing when to use what

In TypeScript, both interface and type alias can be used to define the shape of an object. However, there are some differences and nuances between them. Here are the key differences:

question typescript July 20, 2024 How to filter a Map based on a condition in Typescript?

In TypeScript, you can filter a Map based on a condition using the Map’s built-in methods along with some of JavaScript’s array methods. Since Map is iterable, you can convert it to an array, apply the filter, and then convert it back to a Map. Here’s how you can do it:

question front-end javascript August 28, 2024 8 best Javascript libraries for building fast-changing tables

For handling fast-changing tables in JavaScript, you’ll want libraries that are optimized for performance, support real-time data updates, and are flexible enough to handle a wide range of use cases. Here are some of the best libraries: