-
Notifications
You must be signed in to change notification settings - Fork 27k
Description
🚀 feature request
Relevant Package
@angular/compiler
Description
Optional chaining[1] reached stage 4. We've been supporting similar syntax in templates for a while now, calling it the "safe navigation operator"[2]. For simplicity and smaller payload, we can consider aligning with the spec in future versions of the framework.
There are a couple of semantical and syntactical differences between optional chaining and safe navigation.
Syntax
Optional chaining has the following syntax:
obj?.prop // optional static property access
obj?.[expr] // optional dynamic property access
func?.(...args) // optional function or method callSafe navigation supports only direct property access. Optional chaining supports this, as well as, method calls and function calls. Function calls are particularly useful in iterators:
iterator.return?.()Semantics
With optional chaining, the expression a?.b will be translated to a == null ? undefined : a.b. In Angular, the semantics of the same expression would be null == a ? null : a.b.
If a is null or undefined, the expression typeof a?.b would evaluate to "object" with optional chaining and "undefined" in Angular's safe navigation operator.
Except the mentioned difference above, method calls are compiled similarly:
a?.b()
a == null ? undefined : a.b()In both, optional chaining and safe navigation in templates, stacking the operators is translated the same way: (a?.b).c?.d becomes null == a ? null : null == a.b.c ? null : a.b.c.d.
Another difference seems to be the way parentheses are handled. The optional chaining spec defines that null==e.foo?null:e.foo.b.c should be translated to (a == null ? undefined : a.b).c. In Angular the same expression translates to null == a ? null : a.b.c.
PS: looks like the last issue is fixed by #34221.
[1] Optional chaining spec https://github.com/tc39/proposal-optional-chaining
[2] Safe navigation https://angular.io/guide/template-syntax#safe-navigation-operator