Skip to main content

non-nullable-type-assertion-style

Enforce non-null assertions over explicit type casts.

🔒

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.

💭

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 assertion
  • as: 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 !.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/non-nullable-type-assertion-style": "warn"
}
};

Examples

const maybe = Math.random() > 0.5 ? '' : undefined;

const definitely = maybe as string;
const alsoDefinitely = <string>maybe;

Options

This rule is not configurable.

When Not To Use It

If you don't mind having unnecessarily verbose type casts, you can avoid this rule.

Resources