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 react September 28, 2024 How to add a custom element to a Next.js/Typescript project?

Let’s say I have a custom element setapp-badge that I want to use in my tsx files. If I go ahead and use it, the compiler will throw an error and Next.js will fail to build. It seems the problem might be a combination of how Next.js, TypeScript, and custom elements work together. Therefore, let’s try an approach that avoids the namespace/module issues while ensuring custom elements are recognized in a Next.js/TypeScript project.

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

Filtering an array based on a condition in TypeScript is straightforward and similar to how you would do it in JavaScript. TypeScript adds type safety to the process, ensuring that your code is more robust and less error-prone.

question typescript July 28, 2024 How to pass a generic JSON object as a parameter to a method in TypeScript?

If you want to allow any JSON object without specifying its structure, you can use the object type, Record<string, any>, or simply any. However, each approach has its own implications for type safety and flexibility.

Like my work?

Please, feel free to reach out. I would be more than happy to chat.