no-confusing-non-null-assertion
Disallow non-null assertion in locations that may be confusing.
🔒
Extending "plugin:@typescript-eslint/strict"
in an ESLint configuration enables this rule.
🛠
Some problems reported by this rule are automatically fixable by the --fix
ESLint command line option.
💡
Some problems reported by this rule are manually fixable by editor suggestions.
Using a non-null assertion (!
) next to an assign or equals check (=
or ==
or ===
) creates code that is confusing as it looks similar to a not equals check (!=
!==
).
a! == b; // a non-null assertions(`!`) and an equals test(`==`)
a !== b; // not equals test(`!==`)
a! === b; // a non-null assertions(`!`) and an triple equals test(`===`)
This rule flags confusing !
assertions and suggests either removing them or wrapping the asserted expression in ()
parenthesis.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-confusing-non-null-assertion": "warn"
}
};
Examples
- ❌ Incorrect
- ✅ Correct
interface Foo {
bar?: string;
num?: number;
}
const foo: Foo = getFoo();
const isEqualsBar = foo.bar! == 'hello';
const isEqualsNum = 1 + foo.num! == 2;
interface Foo {
bar?: string;
num?: number;
}
const foo: Foo = getFoo();
const isEqualsBar = foo.bar == 'hello';
const isEqualsNum = (1 + foo.num!) == 2;
Options
This rule is not configurable.
When Not To Use It
If you don't care about this confusion, then you will not need this rule.