TypeScript 中 Type ‘X’ is not assignable to type ‘boolean’ 错误
“ Type ‘X’ is not assignable to type ‘boolean’ ” 当将非布尔值分配给需要布尔值的值时,会发生 TypeScript 错误。 要解决该错误,需要将值转换为布尔值或使用类型保护在赋值之前验证该值是否为布尔值。
下面是错误如何发生的示例。
const str = 'hello';
// ⛔️ Error: Type 'string' is not
// assignable to type 'boolean'.ts(2322)
const bool: boolean = str;
str 变量存储一个字符串,而 bool 变量期望被分配一个布尔值。
例如,我们可以通过将值转换为布尔值来实现。
const str = 'hello';
const bool: boolean = Boolean(str);
console.log(bool); // ?️ true
通过将值转换为布尔值,我们确保赋值的两侧具有兼容的类型。
如果该值可以是布尔值但也可以是另一种类型,则可以在赋值之前使用类型保护。
const example = 'hello';
const bool: boolean = typeof example === 'boolean' ? example : false;
console.log(bool); // ?️ false
我们使用三元运算符来检查示例变量是否具有布尔类型。
如果是,则将其分配给 bool 变量,否则我们使用 false 值作为后备。
如果您绝对确定该值是布尔值,则可以使用类型断言来解决错误。
const example: unknown = true;
const bool: boolean = example as boolean;
console.log(bool); // ?️ false
我们有效地告诉 TypeScript example 将是一个布尔值,不用担心。
因此,根据我们的用例,可以通过向左或向右更新值的类型并使它们兼容来解决错误。
总结
“Type ‘X’ is not assignable to type ‘boolean’” 当将非布尔值分配给需要布尔值的值时,会发生 TypeScript 错误。 要解决该错误,需要将值转换为布尔值或使用类型保护在赋值之前验证该值是否为布尔值。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。