-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: add docs for no-optional-chaining
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
# no-optional-chaining | ||
|
||
This prevents the use of Optional Chaining: | ||
|
||
```js | ||
const baz = obj?.foo?.bar?.baz; // 42 | ||
``` | ||
These will not be allowed because they are not supported in the following browsers: | ||
- Edge (any version at the time of writing) | ||
- Safari (any version at the time of writing) | ||
- Firefox (any version at the time of writing) | ||
- Chrome (any version at the time of writing) | ||
## What is the Fix? | ||
If the expression is short, you can consider using a ternary operator: | ||
```js | ||
// these are equivalent: | ||
foo?.bar | ||
foo == null ? void 0 : foo.bar; | ||
``` | ||
You can also use the Logical OR operator to avoid throwing, although these can look messy: | ||
```js | ||
const baz = (((obj || {}).foo || {}).bar || {}).baz | ||
``` | ||
Lastly, you could consider using a utility function such as [lodash' `get`](https://lodash.com/docs/4.17.15#get) | ||
```js | ||
const baz = _.get(obj, 'foo.bar.baz') | ||
``` | ||
This can be safely disabled if you intend to compile code with the `@babel/plugin-proposal-optional-chaining` Babel plugin. |