对象属性前的?是什么含义?Angular7中TS文件为何不支持?
?. 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 ifobjectisnullorundefinedfirst. If it is, the expression immediately returnsundefinedinstead 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:
- Stick with the traditional null check: Replace
if (object?.foo)withif (object && object.foo). This is fully compatible with TypeScript 3.1 and achieves the same safe access. - 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 yourpackage.jsonto settypescriptto^3.7.0and runnpm installto update.
内容的提问来源于stack exchange,提问作者Mateus Martins

