Angular 12迁移后模板类型检查报错问题求助
Angular 8升级到12后联合类型模板类型检查错误的解决办法
问题原因
Angular 12默认启用了strictTemplates严格模板类型检查,相比之前版本对TypeScript类型规则的执行更严格。之前的版本允许你在模板中访问联合类型里某一成员没有的属性,现在会严格按照类型规则抛出TS2339错误。
可行解决方法
1. 模板内类型收窄(推荐方案)
通过类型守卫明确区分联合类型的成员,让TypeScript确认当前对象拥有message属性:
- 若两个接口有专属区分字段(比如
type标识),直接用*ngIf做判断:
<div *ngFor="let statut of listeStatut"> <!-- 假设CommentaireModel有type: 'comment',HistoriqueStatutModel有type: 'statut' --> <p *ngIf="statut.type === 'comment'">{{ statut.message }}</p> </div>
- 若无区分字段,在组件类中定义自定义类型守卫函数:
isCommentaire(item: HistoriqueStatutModel | CommentaireModel): item is CommentaireModel { return (item as CommentaireModel).message !== undefined; }
然后在模板中调用该函数做判断:
<div *ngFor="let statut of listeStatut"> <p *ngIf="isCommentaire(statut)">{{ statut.message }}</p> </div>
2. 修正接口类型定义
如果业务上message属性本就应该存在于HistoriqueStatutModel中,直接修改接口添加该字段(根据需求设为必填或可选):
interface HistoriqueStatutModel { // 原有属性 message?: string; // 可选属性,根据实际业务调整 }
3. 临时降低模板检查严格度(不推荐)
如果需要快速临时解决问题,可以在tsconfig.json中关闭严格模板检查,但这会丧失类型安全的保障,仅建议作为过渡方案:
{ "angularCompilerOptions": { "strictTemplates": false } }
内容的提问来源于stack exchange,提问作者Amir Choubani
相关产品推荐
相关产品推荐

