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

对象属性前的?是什么含义?Angular7中TS文件为何不支持?

Understanding the ?. Operator and Your Angular/TypeScript Error

Hey there! Let's break this down so it makes total sense.

What does the ?. (Optional Chaining Operator) mean?

That little ?. is called the optional chaining operator, and it's a huge time-saver for safely accessing nested object properties. Here's how it works:

  • When you write object?.foo, it checks if object is null or undefined first. If it is, the expression immediately returns undefined instead of throwing a "cannot read property 'foo' of undefined" error.
  • Without it, you'd have to write verbose checks like if (object && object.foo) to avoid runtime errors.

You're already using it correctly in Angular templates—Angular has supported a similar syntax (called the safe navigation operator) in templates for a long time, which is why that works smoothly. It serves the same purpose as the ES2020 optional chain, but Angular's template parser handles it internally even if your TypeScript version doesn't support the official operator yet.

Why are you getting TS1005/TS1109 errors in your TypeScript files?

The issue boils down to TypeScript version compatibility. Here's the key context:

  • Angular 7.3.9 is paired with TypeScript ~3.1.x by default.
  • The official ?. optional chaining operator was added to TypeScript in version 3.7, which came out after Angular 7 was released.

Since your project's TypeScript version doesn't recognize the ?. syntax, the compiler throws errors like TS1005 (unexpected token) or TS1109 (expression expected)—it just doesn't know what to do with that operator.

How to fix this?

You have two solid options:

  1. Stick with the traditional null check: Replace if (object?.foo) with if (object && object.foo). This is fully compatible with TypeScript 3.1 and achieves the same safe access.
  2. Upgrade TypeScript (with caution): If you want to use ?. in TS files, you can try upgrading your TypeScript version to 3.7+. However, note that Angular 7 wasn't officially tested with TS 3.7, so you might run into minor compatibility issues. If you go this route, update your package.json to set typescript to ^3.7.0 and run npm install to update.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:02:41