How to fix the forbidden non-null assertion in TypeScript and React?

Matthew C.
jump to solution

The Problem

When using typescript-eslint in a JavaScript application, you may encounter the following error:

@typescript-eslint/no-non-null-assertion
warning: Forbidden non-null assertion

The following example code would cause this error:

const loggedInUsername = "bob";

const users = [
  { name: "Steven", age: 12 },
  { name: "Lisa", age: 32 }
];

const loggedInUser = users.find((u) => u.name === loggedInUsername);
console.log(loggedInUser!.age);

You can see a live demo of this error in this typescript-eslint playground.

For this error to occur, the eslintrc file has the “no-non-null-assertion” rule set to "error":

"rules": {
  "@typescript-eslint/no-non-null-assertion": "error"
}

The Non-null Assertion Operator (Postfix !) assertion removes the null and undefined types from a value. To use it, add the ! symbol after an expression like in the console log example above. When your TypeScript configuration is set to do "strictNullChecks", use the non-null assertion operator to bypass the null and undefined type checks. It should only be used if you know a specific value won’t be null or undefined at runtime.

The Solution

Your error message may include a solution to the error:

Consider using the optional chain operator `?.` instead. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator.

To fix the example code above, use the optional chain operator when accessing the age property of the loggedInUser:

console.log(loggedInUser?.age);

If the age property does not exist on the loggedInUser object, the expression will result in undefined instead of throwing an error.

How do you show or hide elements in React?
Matthew C.
How do you loop inside React JSX?
Naveera A.
React TypeError useState
Shivan M.

Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Sentry