TypeScript中'string | boolean'无法赋值给'never'报错排查
TypeScript类属性循环赋值的类型错误解析
问题代码
const creditRiskRatingKeys = [ 'applicant_id', 'is_dirty', ] as const; const dict = { applicant_id: 'test_id', is_dirty: true, } class CreditRiskRating { applicant_id: string = ''; is_dirty: boolean = false; fillQuestionDictionaryToModel() { for (const key of creditRiskRatingKeys) { this[key] = dict[key]; // Type 'string | boolean' is not assignable to type 'never'. } } }
错误原因
你忽略了TypeScript对联合类型属性赋值的严格检查逻辑:
key的类型是'applicant_id' | 'is_dirty'(即keyof CreditRiskRating),此时this[key]的类型是string | boolean,dict[key]的类型也是string | boolean。- 但TypeScript无法在循环的单次迭代中,确认当前
key对应的this[key]类型和dict[key]类型完全匹配(比如applicant_id对应string,is_dirty对应boolean)。 - 它会将
this[key]的类型解析为所有属性类型的交集,而string和boolean的交集是never,因此抛出类型不兼容的错误。
可行解决方案
1. 类型断言快速修复
直接断言赋值两边类型匹配:
this[key] = dict[key] as typeof this[key];
2. 泛型辅助函数保证类型安全
通过泛型函数约束每个key对应的类型严格一致:
class CreditRiskRating { applicant_id: string = ''; is_dirty: boolean = false; private assign<K extends keyof CreditRiskRating>(key: K, value: CreditRiskRating[K]) { this[key] = value; } fillQuestionDictionaryToModel() { for (const key of creditRiskRatingKeys) { this.assign(key, dict[key] as CreditRiskRating[typeof key]); } } }
3. 对齐dict与类的类型定义
给dict指定CreditRiskRating类型,确保结构和类型完全匹配:
const dict: CreditRiskRating = { applicant_id: 'test_id', is_dirty: true, } // 此时循环赋值无需额外处理,TypeScript可自动推断类型匹配
内容的提问来源于stack exchange,提问作者Alireza Ahmadi
相关产品推荐
相关产品推荐

