Disallow the use of optional chaining in an expression where the undefined value would raise an error.

Why is this an issue?

The optional chaining operator ?. allows to access a deeply nested property, returning undefined if the property or any intermediate object is undefined.

This usually means that we expect the expression to evaluate as undefined in some cases. Therefore, using the optional chaining operator in a context where returning undefined is forbidden can lead to errors.

What is the potential impact?

Since optional chaining represents multiple execution branches, having an error thrown in such a context can be hard to debug.

How to fix it

You should provide fallbacks for when the optional chaining operator is used to avoid runtime errors.

Code examples

Noncompliant code example

new (foo?.bar)();
const { foo } = bar?.baz;
const foo = [...bar?.baz]

Compliant solution

new (foo?.bar ?? baz)()
const { foo } = bar?.baz || {}
const foo = bar?.baz ? [...bar.baz] : []