The optional chaining(?.
) expression can short-circuit with undefined
. Therefore, treating an evaluated optional chaining expression as a function, object, number, etc., can cause TypeError or unexpected results.
This rule disallows some cases that might be an TypeError.
Examples of incorrect code for this rule:
/*eslint no-unsafe-optional-chaining: "error"*/
(obj?.foo)();
(obj?.foo).bar;
(obj?.foo)`template`;
new (obj?.foo)();
[...obj?.foo];
bar(...obj?.foo);
Examples of correct code for this rule:
/*eslint no-unsafe-optional-chaining: "error"*/
(obj?.foo)?.();
obj?.foo?.bar;
(obj?.foo ?? bar)`template`;
new (obj?.foo ?? bar)();
var baz = {...obj.?foo};
This rule has an object option:
disallowArithmeticOperators
: Disallow arithmetic operation on optional chaining expression (Defaultfalse
). If this istrue
, this rule warns arithmetic operations on optional chaining expression which possibly result inNaN
.
Examples of additional incorrect code for this rule with the { "disallowArithmeticOperators": true }
option:
/*eslint no-unsafe-optional-chaining: ["error", { "disallowArithmeticOperators": true }]*/
obj?.foo + bar;
obj?.foo * bar;
+obj?.foo;
baz += obj?.foo;