prefer-optional-chain
Enforce using concise optional chain expressions instead of chained logical ands.
Extending "plugin:@typescript-eslint/strict"
in an ESLint configuration enables this rule.
Some problems reported by this rule are manually fixable by editor suggestions.
?.
optional chain expressions provide undefined
if an object is null
or undefined
.
Because the optional chain operator only chains when the property value is null
or undefined
, it is much safer than relying upon logical AND operator chaining &&
; which chains on any truthy value.
It is also often less code to use ?.
optional chaining than &&
truthiness checks.
This rule reports on code where an &&
operator can be safely replaced with ?.
optional chaining.
module.exports = {
"rules": {
"@typescript-eslint/prefer-optional-chain": "warn"
}
};
Examples
- ❌ Incorrect
- ✅ Correct
foo && foo.a && foo.a.b && foo.a.b.c;
foo && foo['a'] && foo['a'].b && foo['a'].b.c;
foo && foo.a && foo.a.b && foo.a.b.method && foo.a.b.method();
(((foo || {}).a || {}).b || {}).c;
(((foo || {})['a'] || {}).b || {}).c;
// this rule also supports converting chained strict nullish checks:
foo &&
foo.a != null &&
foo.a.b !== null &&
foo.a.b.c != undefined &&
foo.a.b.c.d !== undefined &&
foo.a.b.c.d.e;
foo?.a?.b?.c;
foo?.['a']?.b?.c;
foo?.a?.b?.method?.();
foo?.a?.b?.c?.d?.e;
There are a few edge cases where this rule will false positive. Use your best judgement when evaluating reported errors.
Options
This rule is not configurable.
When Not To Use It
If you don't mind using more explicit &&
s, you don't need this rule.