src/content/docs/linter/rules/use-optional-chain.mdx
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs> <TabItem label="JavaScript (and super languages)" icon="seti:javascript"> ## Summary - Rule available since: `v1.0.0` - Diagnostic Category: [`lint/complexity/useOptionalChain`](/reference/diagnostics#diagnostic-category) - This rule is **recommended**, meaning it is enabled by default. - This rule has an [**unsafe**](/linter/#unsafe-fixes) fix. - The default severity of this rule is [**warning**](/reference/diagnostics#warning). - Sources: - Same as [`@typescript-eslint/prefer-optional-chain`](https://typescript-eslint.io/rules/prefer-optional-chain){
"linter": {
"rules": {
"complexity": {
"useOptionalChain": "error"
}
}
}
}
Enforce using concise optional chain instead of chained logical expressions.
TypeScript 3.7 introduced support for the optional chain operator, which was later standardized and included in the ECMAScript specification.
This operator allows you to safely access properties and methods on objects when they are potentially null or undefined.
The optional chain operator only chains when the property value is null or undefined.
It is much safer than relying upon logical operator chaining; which chains on any truthy value.
foo && foo.bar && foo.bar.baz && foo.bar.baz.buzz
foo.bar && foo.bar.baz.buzz
foo !== undefined && foo.bar != undefined && foo.bar.baz !== null && foo.bar.baz.buzz
((foo || {}).bar || {}).baz;
(await (foo1 || {}).foo2 || {}).foo3;
(((typeof x) as string) || {}).bar;
foo && bar;
foo || {};
(foo = 2 || {}).bar;
foo || foo.bar;
foo["some long"] && foo["some long string"].baz