Angular中使用?.语法简化patchValue赋值是否合法?
关于可选链语法简化代码的合法性分析
你编写的简化代码语法本身是合法的,编译器报错通常是以下几种原因:
TypeScript版本不兼容:可选链(
?.)是TypeScript 3.7及以上版本才支持的特性,如果你的项目TS版本低于3.7,编译器无法识别该语法,直接报错。类型未处理完整:如果
stepConfigEvento.pratica本身可能为null或undefined,仅在stepConfigEvento后加可选链不够,需要给pratica也加上可选链,否则TS编译器会检测到类型错误:
this.formGroup.patchValue({ codAzione: this.stepConfigEvento?.pratica?.azione, codRegola: this.stepConfigEvento?.pratica?.regola })
- 项目配置问题:若为Angular或TS项目,需确保
tsconfig.json的compilerOptions开启了对应特性:
{ "compilerOptions": { "target": "ES2020", "lib": ["ES2020"], "strictNullChecks": true } }
另外注意:原代码中stepConfigEvento不存在时赋值null,而简化后的代码会赋值undefined。如果表单控件不接受undefined,需搭配空值合并运算符(??)确保赋值null:
this.formGroup.patchValue({ codAzione: this.stepConfigEvento?.pratica?.azione ?? null, codRegola: this.stepConfigEvento?.pratica?.regola ?? null })
内容的提问来源于stack exchange,提问作者rekotc
相关产品推荐
相关产品推荐

