Rule Proposal: no-unsafe-optional-chaining
See original GitHub issuePlease describe what the rule should do:
Disallow the unsafe uses of optional chaining.
What new ECMAScript feature does this rule relate to?
Optional chaining
What category of rule is this? (place an “X” next to just one item)
[x] Warns about a potential error (problem)
Provide 2-3 code examples that this rule will warn about:
//✖ BAD (TypeError)
(obj?.foo).bar
(obj?.foo)()
(obj?.foo)`template`
new (obj?.foo)()
class A extends obj?.foo {}
//✔ GOOD
obj?.foo.bar
obj?.foo()
(obj?.foo ?? val).bar
(obj?.foo ?? val)()
(obj?.foo ?? val)`template`
new (obj?.foo ?? val)()
class A extends obj?.foo ?? B {}
// Unrelated (no-extra-parens rule will remove those parentheses)
(obj?.foo)?.bar
(obj?.foo)?.()
(obj.foo)?.bar
(obj.foo)?.()
[EDIT] With disallowArithmeticOperators: true
(defaults to false
), additionally disallows operators +
, -
, *
, /
, and **
because will generate NaN
(or unexpected text). It still allows the operators of comparison, bitwise, logical, and relational.
//✖ BAD
obj?.foo + bar
obj?.foo - bar
obj?.foo * bar
obj?.foo / bar
obj?.foo % bar
obj?.foo ** bar
+obj?.foo
-obj?.foo
var v += obj?.foo
var v -= obj?.foo
var v *= obj?.foo
var v /= obj?.foo
var v %= obj?.foo
var v **= obj?.foo
//✔ GOOD
(obj?.foo ?? val) + bar
var v += obj?.foo ?? val
Why should this rule be included in ESLint (instead of a plugin)?
The parentheses around optional chaining disconnect chaining and change the behavior. This is different behavior from well-known non-optional member accesses. This rule warns potential TypeError risks around the difference. This is about a language feature.
Are you willing to submit a pull request to implement this rule?
Yes.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:9
- Comments:6 (6 by maintainers)
Top GitHub Comments
Makes sense to me 👍
Hi 😃 @mysticatea Could I work on it?