Skip to main content

non-nullable-type-assertion-style

Enforce non-null assertions over explicit type assertions.

🔧

Some problems reported by this rule are automatically fixable by the --fix ESLint command line option.

💭

This rule requires type information to run, which comes with performance tradeoffs.

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 assertion is doing the same job as a ! would, and suggests fixing the code to be an !.

eslint.config.mjs
export default defineConfig({
rules: {
"@typescript-eslint/non-nullable-type-assertion-style": "error"
}
});

Try this rule in the playground ↗

Examples​

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

const definitely = maybe as string;
const alsoDefinitely = <string>maybe;
Open in Playground

Options​

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 Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

Resources​