You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目中TypeScript报错:boolean类型无法赋值给never类型

解决TypeScript错误:Type boolean is not assignable to type never

问题原因

TypeScript无法通过typeof this.testObject[key] === 'boolean'这个运行时检查,将key的类型缩小到仅对应布尔属性的键。它依然认为this.testObject[key]可能是string | number | boolean的联合类型,而true无法匹配这个联合类型,最终触发never类型赋值错误。

解决方案

方案1:类型断言(快速解决)

直接通过类型断言告诉TypeScript当前属性是布尔类型:

toogleVal(key: keyof TestInterface): void {
  if (key in this.testObject && typeof this.testObject[key] === 'boolean') {
    this.testObject[key] = true as typeof this.testObject[key];
  }
}

方案2:自定义类型守卫(更严谨)

创建一个类型守卫函数,帮助TypeScript识别当前key对应的是布尔属性:

// 自定义类型守卫
function isBooleanKey<T>(obj: T, key: keyof T): key is keyof { [K in keyof T]: T[K] extends boolean ? K : never } {
  return typeof obj[key] === 'boolean';
}

// 组件中的方法
toogleVal(key: keyof TestInterface): void {
  if (isBooleanKey(this.testObject, key)) {
    this.testObject[key] = true;
  }
}

方案3:限定参数为布尔属性键(最安全)

如果这个方法只需要处理布尔类型的属性,可以直接限定参数类型为TestInterface中布尔属性的键:

// 定义工具类型,提取对象中布尔属性的键
type BooleanKeys<T> = { [K in keyof T]: T[K] extends boolean ? K : never }[keyof T];

// 方法参数仅接受布尔属性的键
toogleVal(key: BooleanKeys<TestInterface>): void {
  this.testObject[key] = true;
}

这种方式还能在调用时做类型校验,避免传入非布尔属性的键。

内容的提问来源于stack exchange,提问作者miholzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 18:45:03