non-nullable-type-assertion-style
Enforce non-null assertions over explicit type casts.
Extending "plugin:@typescript-eslint/stylistic-type-checked"
in an ESLint configuration enables this rule.
Some problems reported by this rule are automatically fixable by the --fix
ESLint command line option.
This rule requires type information to run.
There are two common ways to assert to TypeScript that a value is its type without null
or undefined
:
!
: Non-null assertionas
: Traditional type assertion with a coincidentally equivalent type
!
non-null assertions are generally preferred for requiring less code and being harder to fall out of sync as types change.
This rule reports when an as
cast is doing the same job as a !
would, and suggests fixing the code to be an !
.
module.exports = {
"rules": {
"@typescript-eslint/non-nullable-type-assertion-style": "error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
const maybe: string | undefined = Math.random() > 0.5 ? '' : undefined;
const definitely = maybe as string;
const alsoDefinitely = <string>maybe;
Open in Playgroundconst maybe: string | undefined = Math.random() > 0.5 ? '' : undefined;
const definitely = maybe!;
const alsoDefinitely = maybe!;
Open in PlaygroundOptions
This rule is not configurable.
When Not To Use It
If you don't mind having unnecessarily verbose type assertions, you can avoid this rule.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting. See Performance Troubleshooting if you experience performance degredations after enabling type checked rules.