Ionic升级至6.20.6+Angular15后出现Type 'string'不可赋值给null错误
解决Type 'string' is not assignable to type 'null'类型错误
问题原因
你的代码中showLevel1初始值设为null,TypeScript会自动推断它的类型为null,而toggleLevel1方法中尝试给它赋值string类型的idx,导致类型不匹配,触发TypeScript编译错误。Angular 15升级后,TypeScript的严格类型检查规则更严格,之前的隐式类型兼容不再被允许。
修复方案
显式声明showLevel1和showLevel2的类型为string | null,让它们同时支持string和null两种类型值:
export class AppComponent { public appPages: any; showLevel1: string | null = null; showLevel2: string | null = null; @ViewChildren(IonRouterOutlet) routerOutlets: QueryList<IonRouterOutlet>; clearLevel() { this.showLevel1 = null; this.showLevel2 = null; // this.showLevel3 = null; } toggleLevel1(idx: string) { if (this.isLevel1Shown(idx)) { this.showLevel1 = null; } else { this.showLevel1 = idx; } } isLevel1Shown(idx: string) { return this.showLevel1 === idx; } }
说明
通过联合类型string | null明确变量的取值范围,既符合你代码中“展开时赋值菜单索引、收起时设为null”的逻辑,也满足TypeScript的严格类型校验要求,解决升级后的编译错误。
内容的提问来源于stack exchange,提问作者Dr NVS
相关产品推荐
相关产品推荐

