Typescript optional chaining and ESLint `no-unused-expressions`
Typescript 3.7 introduced the long awaited optional chaining syntax.
The short gist is that this
const foo = bar && bar.tea && bar.tea.cup;
can now simply be
const foo = bar?.tea?.cup;
When using the commonly enabled ESLint rule no-unused-expressions
, however, this can lead to false positives:
foo?.bar();
// ^^^^^^^^^^
// Expected an assignment or function call and instead saw an expression. eslint(no-unused-expressions)
Luckily, Typescript releases enhanced ESLint rules under @typescript-eslint
. To use the TS version of the same rule, turn the original one off, and enable the extended one in your .eslintrc
:
'no-unused-expressions': 'off',
'@typescript-eslint/no-unused-expressions': 'error',
The above snippet now passes lint as expected.