Skip to content

eslint/no-unsafe-optional-chaining Restriction

What it does

Disallow use of optional chaining in contexts where the undefined value is not allowed

Why is this bad?

The optional chaining (?.) expression can short-circuit with a return value of undefined. Therefore, treating an evaluated optional chaining expression as a function, object, number, etc., can cause TypeError or unexpected results. For example:

Example

javascript
var obj = undefined;
1 in obj?.foo; // TypeError
with (obj?.foo); // TypeError
for (bar of obj?.foo); // TypeError
bar instanceof obj?.foo; // TypeError
const { bar } = obj?.foo; // TypeError

References

Released under the MIT License.