Solve - Type 'X' is not assignable to type 'boolean' in TS

avatar

Borislav Hadzhiev

Mon Mar 07 20222 min read

banner

Photo by Dhery Moelz

Solve - Type 'X' is not assignable to type 'boolean' in TS #

The "Type 'X' is not assignable to type 'boolean'" TypeScript error occurs when a value that is not a boolean is assigned to something that expects a boolean. To solve the error, convert the value to a boolean or use a type guard to verify value is a boolean before the assignment.

Here is an example of how the error occurs.

index.ts
const str = 'hello'; // ⛔️ Error: Type 'string' is not // assignable to type 'boolean'.ts(2322) const bool: boolean = str;

The str variable stores a string and the bool variable expects to get assigned a boolean.

The types of the two values are incompatible, so the error is thrown.

To solve the error, we have to make sure that the values on the two sides of the assignment have compatible types.

For example, you could do that by converting the value to a boolean.

index.ts
const str = 'hello'; const bool: boolean = Boolean(str); console.log(bool); // 👉️ true

By converting the value to a boolean, we make sure that the two sides of the assignment have compatible types.

If the value could be boolean but also another type, you can use a type guard before the assignment.

index.ts
const example = 'hello'; const bool: boolean = typeof example === 'boolean' ? example : false; console.log(bool); // 👉️ false

We used a ternary operator to check if the example variable has a type of boolean.

If it does, it gets assigned to the bool variable, otherwise we use a false value as a fallback.

This way we can be sure that the bool variable will always get assigned a boolean, even if the example variable might be of a different type.

If you are absolutely sure that the value is a boolean, you can use a type assertion to solve the error.

index.ts
const example: unknown = true; const bool: boolean = example as boolean; console.log(bool); // 👉️ false
Type assertions are used when we have information about the type of a value that TypeScript can't know about.

We effectively tell TypeScript that example will be a boolean and not to worry about it.

The cause of the "Type 'X' is not assignable to type boolean" error is that the types of the values on the left an right hand sides are not compatible.

So depending on your use case, you could solve the error by updating the type of the value to the left or right and making them compatible.

Use the search field on my Home Page to filter through my more than 1,000 articles.