Mon Mar 07 2022·2 min read
Photo by Dhery Moelz
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.
const str = 'hello'; // ⛔️ Error: Type 'string' is not // assignable to type 'boolean'.ts(2322) const bool: boolean = str;
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.
For example, you could do that by converting the value to a boolean.
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
before the assignment.
const example = 'hello'; const bool: boolean = typeof example === 'boolean' ? example : false; console.log(bool); // 👉️ false
We used a
to check if the
example variable has a type of
If it does, it gets assigned to the
bool variable, otherwise we use a
value as a fallback.
boolvariable will always get assigned a boolean, even if the
examplevariable 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.
const example: unknown = true; const bool: boolean = example as boolean; console.log(bool); // 👉️ false
We effectively tell TypeScript that
example will be a boolean and not to worry
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.