no-non-null-asserted-optional-chain
Disallow non-null assertions after an optional chain expression.
Extending "plugin:@typescript-eslint/recommended"
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
.
Using a !
non-null assertion to assert the result of an ?.
optional chain expression is non-nullable is likely wrong.
Most of the time, either the object was not nullable and did not need the
?.
for its property lookup, or the!
is incorrect and introducing a type safety hole.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-non-null-asserted-optional-chain": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-non-null-asserted-optional-chain": "error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
foo?.bar!;
foo?.bar()!;
Open in Playgroundfoo?.bar;
foo?.bar();
Open in PlaygroundOptions
This rule is not configurable.
When Not To Use It
If your project's types don't yet fully describe whether certain values may be nullable, such as if you're transitioning to strictNullChecks
, this rule might create many false reports.
You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.