Lint Rules

noNonNullAssertion (since v11.0.0)

Disallow non-null assertions using the ! postfix operator.

TypeScript’s ! non-null assertion operator asserts to the type system that an expression is non-nullable, as in not null or undefined. Using assertions to tell the type system new information is often a sign that code is not fully type-safe. It’s generally better to structure program logic so that TypeScript understands when values may be nullable.

Examples

Invalid

interface Example {
  property?: string;
}
declare const example: Example;
const includesBaz = foo.property!.includes('baz');
nursery/noNonNullAssertion.js:5:21 lint/nursery/noNonNullAssertion  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━

   Forbidden non-null assertion.
  
    3 │ }
    4 │ declare const example: Example;
  > 5 │ const includesBaz = foo.property!.includes('baz');
                       ^^^^^^^^^^^^^
    6 │ 
  
   Suggested fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator
  
    3 3  }
    4 4  declare const example: Example;
    5  - const·includesBaz·=·foo.property!.includes('baz');
      5+ const·includesBaz·=·foo.property?.includes('baz');
    6 6  
  
(b!! as number) = "test";
nursery/noNonNullAssertion.js:1:2 lint/nursery/noNonNullAssertion ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

   Forbidden non-null assertion.
  
  > 1 │ (b!! as number) = "test";
    ^^^
    2 │ 
  

Valid

interface Example {
  property?: string;
}

declare const example: Example;
const includesBaz = foo.property?.includes('baz') ?? false;